package org.linlinjava.litemall.admin.service.order_manage;


import cn.com.ejiakanghu.core.exception.CheckException;
import cn.com.ejiakanghu.service.LeaseOrderService;
import cn.com.ejiakanghu.service.OrderService;
import cn.ejiakanghu.logistics.service.impl.LogisticBusiBaseServiceImpl;
import cn.ejiakanghu.logistics.service.impl.OrderStateService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.linlinjava.litemall.admin.vo.order_manage.OrderSettingVo;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.config.BizException;
import org.linlinjava.litemall.core.lock_rfid.LockRfidUtil;
import org.linlinjava.litemall.core.lock_rfid.UnLockCabinetGoodsVo;
import org.linlinjava.litemall.core.lock_rfid.UnLockGoodsVo;
import org.linlinjava.litemall.core.util.AgedmallException;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.db.dao.app.AppOrderMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedMallOrderMapper;
import org.linlinjava.litemall.db.dao.order_manage.SubOrderAndCommodityRelatedOperationsMapper;
import org.linlinjava.litemall.db.dto.UserAddressInfo;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.SaleLogisticsDto;
import org.linlinjava.litemall.db.vo.logistics.*;
import org.linlinjava.litemall.db.vo.order_manage.OrderNotDeliverLoadVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.BackendOrderMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.vo.order_manage.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AgedMallOrderService {
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;
    @Resource
    private BackendOrderMapper backendOrderMapper;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private LitemallUserMapper litemallUserMapper;
    @Resource
    private AgedmallLogisticsPackageInfoMapper agedmallLogisticsPackageInfoMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private AgedmallProcessStateService agedmallProcessStateService;
    @Resource
    private AgedmallLeaseGoodsReturnRecordMapper agedmallLeaseGoodsReturnRecordMapper;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private GoodsProductMapper goodsProductMapper;
    @Resource
    private AgedmallOrderSettingMapper agedmallOrderSettingMapper;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private AgedmallOrderSerialService agedmallOrderSerialService;
    @Resource
    private LitemallAftersaleMapper litemallAftersaleMapper;
    @Resource
    private AgedmallReturnGoodsRecordMapper agedmallReturnGoodsRecordMapper;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;
    @Resource
    private AgedMallOrderMapper agedMallOrderMapper;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private AgedmallLgThirdLogisRecordMapper agedmallLgThirdLogisRecordMapper;
    @Resource
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;
    @Resource
    private LeaseOrderService leaseOrderService;
    @Resource
    private SubOrderAndCommodityRelatedOperationsMapper subOrderAndCommodityRelatedOperationsMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LogisticsGoodsUtil logisticsGoodsUtil;
    @Resource
    private AgedmallAnnouncerBaseInfoService agedmallAnnouncerBaseInfoService;
    @Resource
    private AgedmallCloudHouseMapper agedmallCloudHouseMapper;
    @Resource
    private AgedmallExpressMapper agedmallExpressMapper;
    @Resource
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Resource
    private AgedmallCabinetGoodsMapper agedmallCabinetGoodsMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private AgedmallRfidGoodsProductMapper agedmallRfidGoodsProductMapper;
    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;
    @Resource
    private LitemallGoodsMapper litemallGoodsMapper;
    @Resource
    private AgedmallServiceOrderMapper agedmallServiceOrderMapper;
    @Resource
    private LockRfidUtil lockRfidUtil;
    @Resource
    private OrderStateService orderStateService;
    @Resource
    private AgedmallLgMissionManRecordMapper agedmallLgMissionManRecordMapper;
    @Resource
    private AgedmallWxNodepositRecordMapper agedmallWxNodepositRecordMapper;
    @Resource
    private LitemallAddressMapper litemallAddressMapper;
    @Resource
    private AgedmallLgBusiRecordMapper agedmallLgBusiRecordMapper;
    @Resource
    private AgedmallLgBusiImgMapper agedmallLgBusiImgMapper;
    @Resource
    private AgedmallLgBaseInfoService agedmallLgBaseInfoService;
    @Resource
    private AgedmallLgMissionService agedmallLgMissionService;
    @Resource
    private AgedmallHospitalSendSelfLocationMapper agedmallHospitalSendSelfLocationMapper;
    @Autowired
    private OrderService orderService;

    private Logger logger = LoggerFactory.getLogger(AgedMallOrderService.class);

    // shop
    public Object rentOrderList(String phone, String orderSn, Integer state, Integer provinceId, Integer cityId, Integer storeId,
                                LocalDateTime startTime, LocalDateTime endTime, Integer shopId, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Short> states = OrderUtil.backendOrderStatus(state);
        List<OrderListVo> list = backendOrderMapper.list(phone, orderSn, states, provinceId, cityId, storeId, shopId, startTime, endTime);
        list.stream().forEach(p -> {
            List<OrderListGoodsVo> goodsVoList = backendOrderMapper.orderGoodsList(p.getBigOrderId());
            //System.out.println("=====>"+p.getOrderId());
            goodsVoList.stream().forEach(q -> {
                p.setSuboId(q.getSuboId());
                List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
                String spec = "";
                if (CollectionUtils.isNotEmpty(specificationList)) {
                    for (LitemallGoodsProductSpecification specification : specificationList) {
                        spec += "," + specification.getInfoName() + ":" + specification.getName();
                    }
                }
                q.setGoodsSpec(spec.replaceFirst(",", ""));
                q.setOrderStatus(OrderUtil.backendShowType(q.getOrderStatus().shortValue()));
            });
            p.setGoodslist(goodsVoList);
        });
        return ResponseUtil.okList(list);
    }

    /**
     * 各状态 显示模块
     * 待付款     待发货     待自提     待用户收货       使用中     待取货（租赁回收）   待商户收货       待结算     已关闭     已完成
     * 基本信息       有        有        有          有            有          有               有            有                   有
     * 商品列表       有        有        有          有            有          有               有            有                   有
     * 加急预约提示             有
     * 用户收货信息    有        有                    有            有          有               有            有                   有
     * 自提信息                           有
     * 发货包裹                                      有            有           有              有            有                   有
     * 商户收货信息                                                                             有           有                   有
     */
    public Object rentOrderDetail(Integer orderId, Integer state, Integer bigOrderId) {
        //根据子订单id 查询出大订单的id                                                      子订单id
        LitemallOrderItem litemallOrderItem = bigOrderId == null ? litemallOrderItemMapper.selectByPrimaryKey(orderId) : null;
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        if(bigOrderId == null) {
           bigOrderId = litemallOrderItem.getParentId();
        }
        LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(bigOrderId);
        String bigOrderCode = order.getOrderSn();
        //二维码信息
        String baseqrCode = "https://lbb.ejiakanghu.cn/share/order?code=LBB-";
        LitemallUser user = litemallUserMapper.selectByPrimaryKey(order.getUserId());
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(orderId.longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
        //存放每个商品的goodsid
        List<Integer> goodsIdList = new ArrayList<>();
        for (int i = 0; i < litemallOrderGoodsList.size(); i++) {
            goodsIdList.add(litemallOrderGoodsList.get(i).getId());
        }

        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        agedmallLgBaseInfoExample.or().andOrderCodeEqualTo(bigOrderCode).andLgTypeEqualTo(LgBaseInfoLgType.SELFPICKUP.getCode());
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
        //获取自提的包裹id
        Integer baseInfoId = 0;
        for (int i = 0; i < agedmallLgBaseInfoList.size(); i++) {
            AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoList.get(i);
            Long agedmallLgBaseInfoId = agedmallLgBaseInfo.getId();
            LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfoList.get(i).getLgContent());
            List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
            for (int j = 0; j < goodsDataList.size(); j++) {
                LogisticsGoodsData logisticsGoodsData = goodsDataList.get(j);
                for (int k = 0; k < litemallOrderGoodsList.size(); k++) {
                    LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsList.get(k);
                    if (logisticsGoodsData.getOrderGoodsId().equals(litemallOrderGoods.getId())) {
                        baseInfoId = agedmallLgBaseInfoId.intValue();
                        break;
                    }
                }
            }
        }

        //获取二维码所需要的missionId
        AgedmallLgMissionExample agedmallLgMissionExample = new AgedmallLgMissionExample();
        agedmallLgMissionExample.or().andBaseInfoIdEqualTo(baseInfoId);
        AgedmallLgMission agedmallLgMission = agedmallLgMissionMapper.selectOneByExample(agedmallLgMissionExample);
        //拼接字体二维码的地址
        if (null != agedmallLgMission) {
            String missionIsStr = agedmallLgMission.getId().toString();
            orderDetailVo.setQrCode(baseqrCode.concat(missionIsStr));
        }

        //自提码
        String selfCode = stringRedisTemplate.opsForValue().get("self-" + baseInfoId + "-code");

        // 基本信息
        orderDetailVo.setState(state);
        orderDetailVo.setOrderSn(bigOrderCode);
        orderDetailVo.setPayId(order.getPayId());
        orderDetailVo.setAddTime(order.getAddTime());
        orderDetailVo.setSelfCode(selfCode);
        orderDetailVo.setCloseTime(order.getExtractTime());
        orderDetailVo.setPayTime(order.getPayTime());
        // 待发货，是否有加急和预约
        if (OrderUtil.STATUS_PAY == state.shortValue()) {
            int urgentCount = backendOrderMapper.getCountByDeliverySn(bigOrderId, AgedmallShipDictConstant.SHIP_SN_URGENT);
            orderDetailVo.setHasUrgent(urgentCount > 0 ? 1 : 0);
            int subscribeCount = backendOrderMapper.getCountByDeliverySn(bigOrderId, AgedmallShipDictConstant.SHIP_SN_SUBSCRIBE);
            orderDetailVo.setHasSubscribe(subscribeCount > 0 ? 1 : 0);
        }

        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        //子订单id
        orderItemExample.createCriteria().andOrderCodeEqualTo(bigOrderCode).andDeletedEqualTo(false);
        //根据大订单id查询出所有的子订单信息
        List<LitemallOrderItem> orderItemList = litemallOrderItemMapper.selectByExampleSelective(orderItemExample);
        List<OrderDetailSubOrderListVo> subOrderList = orderItemList.stream()
                .map(p -> {
                    OrderDetailSubOrderListVo orderDetailSubOrderListVo = new OrderDetailSubOrderListVo();
                    orderDetailSubOrderListVo.setOrderId(p.getId());
                    //System.out.println("====>"+p.getId());
                    orderDetailSubOrderListVo.setOrderSn(p.getChildOrderCode());
                    orderDetailSubOrderListVo.setRemark(p.getMessage());
                    orderDetailSubOrderListVo.setGoodsType(p.getGoodsType());
                    //查询出每个子订单的门店信息
                    AgedmallStore agedmallStore = agedmallStoreMapper.selectByPrimaryKey(p.getStoreId().longValue());
                    if (null != agedmallStore) {
                        orderDetailSubOrderListVo.setStoreName(agedmallStore.getStoreName());
                        orderDetailSubOrderListVo.setStoreAddress(agedmallStore.getAddressDetail());
                    }
                    List<OrderDetailSubOrderListGoodsVo> goodsList = backendOrderMapper.getOrderDetailSubOrderListGoodsVos(p.getId());
                    goodsList.stream().forEach(q -> {
                        q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
                        List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
                        String spec = "";
                        if (CollectionUtils.isNotEmpty(specificationList)) {
                            for (LitemallGoodsProductSpecification specification : specificationList) {
                                spec += "," + specification.getInfoName() + ":" + specification.getName();
                            }
                        }
                        q.setGoodsSpec(spec.replaceFirst(",", ""));
                    });
                    orderDetailSubOrderListVo.setGoodsList(goodsList);
                    return orderDetailSubOrderListVo;
                }).collect(Collectors.toList());
        orderDetailVo.setSubOrderList(subOrderList);
        LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
        AgedmallStore agedmallStore = agedmallStoreMapper.selectByPrimaryKey(orderItem.getStoreId().longValue());
        // 用户收货信息
        if (OrderUtil.STATUS_SHIP_SELF != state.shortValue()) {
            OrderDetailReceiveVo receiveInfo = new OrderDetailReceiveVo();
            receiveInfo.setReceiverName(order.getConsignee());
            receiveInfo.setReceiverPhone(order.getMobile());
            receiveInfo.setReceiverAddress(order.getAddress());
            receiveInfo.setUserName(user.getNickname());
            receiveInfo.setUserPhone(user.getMobile());
            receiveInfo.setFreightPrice(order.getFreightPrice());
            receiveInfo.setPayType(order.getPayType());
            receiveInfo.setPayAmount(order.getActualPrice());
            receiveInfo.setStoreName(agedmallStore.getStoreName());
            receiveInfo.setStoreAddress(agedmallStore.getAddressDetail());
            orderDetailVo.setReceiveInfo(receiveInfo);
            // 自提信息
        } else {
            List<OrderDetailSelfPickupVo> orderDetailSelfPickupVoList = backendOrderMapper.getOrderDetailSelfPickupVos(orderId);
            if (orderDetailSelfPickupVoList.size() > 0) {
                orderDetailVo.setSelfPickupList(orderDetailSelfPickupVoList.get(0));
            }
        }
        // 发货包裹
        List<OrderDetailPackageVo> packageList = new ArrayList<>();

        AgedmallLgBaseInfoExample baseInfoExample = new AgedmallLgBaseInfoExample();
        List<Integer> lgTypeList = new ArrayList<>();
        lgTypeList.add(1);
        lgTypeList.add(8);
        List<Integer> baseInfoIdList = new ArrayList<>(5);
        //大订单的编号     可以通过子订单的id 查询出大订单的编号
        baseInfoExample.or().andOrderCodeEqualTo(bigOrderCode).andLgTypeIn(lgTypeList);
        List<AgedmallLgBaseInfo> baseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(baseInfoExample);
        List<String> urlString = new ArrayList<>(9);
        if (baseInfoList.size() > 0) {
            Integer storeId = 0;
            //&& null != baseInfoList.get(0).getLgUserConf()
            for (int i = 0; i < baseInfoList.size(); i++) {
                if (!baseInfoList.get(i).getLgIsOver().equals(LgBaseInfoIsOverEnum.CANCEL.getCode())) {
                    //baseInfoIdList.add(baseInfoList.get(i).getId().intValue());
                    OrderDetailPackageVo orderDetailPackageVo = new OrderDetailPackageVo();
                    AgedmallLgMissionExample missionExample = new AgedmallLgMissionExample();
                    missionExample.or().andBaseInfoIdEqualTo(baseInfoList.get(i).getId().intValue());
                    List<AgedmallLgMission> missionList = agedmallLgMissionMapper.selectByExample(missionExample);
                    List<Integer> missionIdList = new ArrayList<>();
                    missionList.forEach(mission -> missionIdList.add(mission.getId()));
                    if (missionIdList.size() > 0) {
                        List<OrderDetailMissionVo> orderDetailMissionVos = agedMallOrderMapper.selectOrderDetailMissionMessage(missionIdList);
                        if (baseInfoList.get(i).getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
                            orderDetailPackageVo.setDeliverySn(0);
                        }
                        for (int j = 0; j < orderDetailMissionVos.size(); j++) {
                            if (orderDetailMissionVos.get(j).getType() == 1) {
                                orderDetailPackageVo.setDistributionUser(orderDetailMissionVos.get(j).getUserName());
                            } else if (orderDetailMissionVos.get(j).getType() == 2) {
                                orderDetailPackageVo.setDeliverySn(orderDetailMissionVos.get(j).getLgExecType());
                                orderDetailPackageVo.setDeliveryTime(orderDetailMissionVos.get(j).getCreatedTime());
                                orderDetailPackageVo.setDeliveryUser(orderDetailMissionVos.get(j).getUserName());
                            } else {
                                //自提时使用到
                                //orderDetailPackageVo.setDeliverySn(orderDetailMissionVos.get(j).getLgExecType());
                                orderDetailPackageVo.setDeliveryTime(orderDetailMissionVos.get(j).getCreatedTime());
                                orderDetailPackageVo.setDistributionUser(orderDetailMissionVos.get(j).getUserName());
                                orderDetailPackageVo.setPhoneNumber(orderDetailMissionVos.get(j).getPhone());
                            }
                            AgedmallLgBusiRecordExample agedmallLgBusiRecordExample = new AgedmallLgBusiRecordExample();
                            AgedmallLgBusiImgExample agedmallLgBusiImgExample = new AgedmallLgBusiImgExample();
                            AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
                            AgedmallLgBusiImg agedmallLgBusiImg = new AgedmallLgBusiImg();
                            //获取自提配货完成的上传的图片
                            for (int m = 0; m < missionIdList.size(); m++) {
                                agedmallLgBusiRecordExample.or().andMissionIdEqualTo(missionIdList.get(m).longValue());
                                agedmallLgBusiRecord = agedmallLgBusiRecordMapper.selectOneByExample(agedmallLgBusiRecordExample);
                                if (null != agedmallLgBusiRecord) {
                                    agedmallLgBusiImgExample.or().andLgBusiIdEqualTo(agedmallLgBusiRecord.getId());
                                    agedmallLgBusiImg = agedmallLgBusiImgMapper.selectOneByExample(agedmallLgBusiImgExample);
                                    //配货完成的图片
                                    if (null != agedmallLgBusiImg) {
                                        String agedmallLgBusiImgUrl = agedmallLgBusiImg.getUrl();
                                        String[] urlArr = agedmallLgBusiImgUrl.split(",");
                                        urlString.addAll(Arrays.asList(urlArr));
                                        orderDetailPackageVo.setImgUrl(urlString);
                                    }
                                }
                            }
                        }
                    }
                    List<OrderDetailDeliveryVo> logistInfo = getLogistInfo(baseInfoList.get(i).getId().intValue());
                    //System.out.println("=======>"+logistInfo.size());
                    AgedmallLgReceiveOrder agedmallLgReceiveOrder = new AgedmallLgReceiveOrder();
                    LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(baseInfoList.get(i).getLgContent());
                    List<Integer> orderGoodsId = new ArrayList<>();
                    commonData.getGoodsDataList().forEach(goods -> orderGoodsId.add(goods.getOrderGoodsId()));
                    List<OrderDetailGoodsVo> goodsList = backendOrderMapper.getOrderDetailPackageGoodsVos(orderGoodsId);
                    goodsList.stream().forEach(q -> {
                        List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
                        String spec = "";
                        if (CollectionUtils.isNotEmpty(specificationList)) {
                            for (LitemallGoodsProductSpecification specification : specificationList) {
                                spec += "," + specification.getInfoName() + ":" + specification.getName();
                            }
                        }
                        q.setGoodsSpec(spec.replaceFirst(",", ""));
                    });
                    storeId = goodsList.get(0).getStoreId();
                    orderDetailPackageVo.setGoodsList(goodsList);
                    orderDetailPackageVo.setPackId(baseInfoList.get(i).getId().intValue());
                    //非自提
                    if (OrderUtil.STATUS_SHIP_SELF != state.shortValue()) {
                        packageList.add(orderDetailPackageVo);
                        orderDetailPackageVo.setStateList(logistInfo);
                    } else {
                        //自提
                        AgedmallLgReceiveOrderExample agedmallLgReceiveOrderExample = new AgedmallLgReceiveOrderExample();
                        agedmallLgReceiveOrderExample.or().andMissionIdEqualTo(missionIdList.get(0).longValue()).andLgBaseInfoIdEqualTo(baseInfoList.get(i).getId());
                        agedmallLgReceiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(agedmallLgReceiveOrderExample);
                        OrderDetailDeliveryVo orderDetailDeliveryVoStart = new OrderDetailDeliveryVo();
                        OrderDetailDeliveryVo orderDetailDeliveryVo = new OrderDetailDeliveryVo();
                        if (logistInfo.size() > 0) {
                            //自提的物流信息
                            // 开始配货  时间  开始配货的完成时间 现在使用的时接单时间
                            orderDetailDeliveryVoStart.setDeliveryState(concatDesc(8, 8, 1,
                                    agedmallLgReceiveOrder.getUserName(), agedmallLgReceiveOrder.getPhone()));
                            orderDetailDeliveryVoStart.setDeliveryTime(agedmallLgReceiveOrder.getCreatedTime());
                            // 完成配货  时间
                            orderDetailDeliveryVo.setDeliveryState(logistInfo.get(0).getDeliveryState());
                            orderDetailDeliveryVo.setDeliveryTime(logistInfo.get(0).getDeliveryTime());
                            orderDetailPackageVo.setOrderDetailDeliveryVo(orderDetailDeliveryVo);

                            AgedmallLgBusiRecordExample agedmallLgBusiRecordExample = new AgedmallLgBusiRecordExample();
                            agedmallLgBusiRecordExample.or().andMissionIdEqualTo(missionIdList.get(0).longValue()).andBusiStatEqualTo(LgMissionIsOverEum.START.getCode());

                            AgedmallLgBusiRecord lgBusiRecord = agedmallLgBusiRecordMapper.selectOneByExample(agedmallLgBusiRecordExample);
                            if (null == lgBusiRecord) {
                                //添加物流流水表
                                AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
                                agedmallLgBusiRecord.setLgType(LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode());
                                //开始配货
                                agedmallLgBusiRecord.setBusiStat(SelfNodeEnum.START.getCode());
                                //agedmallLgBusiRecord.setUpdateTime(LocalDateTime.now());
                                agedmallLgBusiRecord.setCreatedTime(agedmallLgReceiveOrder.getCreatedTime());
                                agedmallLgBusiRecord.setCreatedBy("auto");
                                agedmallLgBusiRecord.setMissionId(missionIdList.get(0).longValue());
                                agedmallLgBusiRecord.setBusiTime(agedmallLgReceiveOrder.getCreatedTime());
                                agedmallLgBusiRecord.setReceiveOrderId(null);
                                agedmallLgBusiRecordMapper.insertSelective(agedmallLgBusiRecord);
                            }
                            List<OrderDetailDeliveryVo> selfDelivery = new ArrayList<>(3);
                            selfDelivery.add(orderDetailDeliveryVoStart);
                            selfDelivery.add(orderDetailDeliveryVo);
                            orderDetailPackageVo.setStateList(selfDelivery);
                        } else {
                            orderDetailPackageVo.setOrderDetailDeliveryVo(null);
                        }
                        orderDetailVo.setOrderDetailPackageVo(orderDetailPackageVo);
                    }
                    if(logistInfo.size() > 0) {
                        OrderDetailDeliveryVo orderDetailDeliveryVo = logistInfo.get(logistInfo.size() - 1);
                        orderDetailVo.setDeliveryTime(orderDetailDeliveryVo.getDeliveryTime());
                    }
                }
            }
            orderDetailVo.setPackageList(packageList);
            orderDetailVo.setStoreId(storeId);

        }
        //用户发货信息
        // 商户收货信息
        List<OrderDetailReturnVo> returnList = new ArrayList<>();
        AgedmallLgBaseInfoExample renturnBaseInfoExample = new AgedmallLgBaseInfoExample();
        List<Integer> lgTypeBackList = new ArrayList<>();
        lgTypeBackList.add(LgBaseInfoLgType.GIVEBACK.getCode());
        lgTypeBackList.add(LgBaseInfoLgType.RETURNTHEGOODS.getCode());
        lgTypeBackList.add(LgBaseInfoLgType.EXCHANGE.getCode());
        lgTypeBackList.add(LgBaseInfoLgType.MAINTAIN.getCode());
        renturnBaseInfoExample.or().andOrderCodeEqualTo(bigOrderCode).andLgTypeIn(lgTypeBackList);
        List<AgedmallLgBaseInfo> backBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(renturnBaseInfoExample);
        for (int i = 0; i < backBaseInfoList.size(); i++) {
            OrderDetailReturnVo returnVo = new OrderDetailReturnVo();
            AgedmallLgMissionExample missionExample = new AgedmallLgMissionExample();
            missionExample.or().andBaseInfoIdEqualTo(backBaseInfoList.get(i).getId().intValue()).andTypeEqualTo(4);
            List<AgedmallLgMission> missionList = agedmallLgMissionMapper.selectByExample(missionExample);
            List<Integer> missionIdList = new ArrayList<>();
            missionList.forEach(mission -> missionIdList.add(mission.getId()));
            List<OrderDetailMissionVo> orderDetailMissionVos = new ArrayList<>(3);
            if (missionIdList.size() > 0) {
                orderDetailMissionVos = agedMallOrderMapper.selectOrderDetailMissionMessage(missionIdList);
                returnVo.setMissionId(missionIdList.get(0));
            }
            if (backBaseInfoList.get(i).getLgIsOver().equals(LgBaseInfoIsOverEnum.END.getCode())) {
                returnVo.setInStoreState(1);
            } else {
                returnVo.setInStoreState(0);
            }
            for (int j = 0; j < orderDetailMissionVos.size(); j++) {
                if (orderDetailMissionVos.get(j).getMissionIsOver().equals(LgMissionIsOverEum.START.getCode())) {
                    returnVo.setApplyTime(orderDetailMissionVos.get(j).getCreatedTime());
                } else if (orderDetailMissionVos.get(j).getMissionIsOver().equals(LgMissionIsOverEum.END.getCode())) {
                    returnVo.setInStoreTime(orderDetailMissionVos.get(j).getCreatedTime());
                }
            }

            List<OrderDetailDeliveryVo> logistInfo = getLogistInfo(backBaseInfoList.get(i).getId().intValue());
            returnVo.setStateList(logistInfo);
            LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(backBaseInfoList.get(i).getLgContent());
            List<Integer> orderGoodsId = new ArrayList<>();
            commonData.getGoodsDataList().forEach(goods -> orderGoodsId.add(goods.getOrderGoodsId()));
            //判断属于哪个子订单
            LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId.get(0));
            List<AgedmallLeaseGoodsReturnRecord> leaseReturnGoodsMessage = appOrderMapper.getLeaseReturnGoodsMessage(orderGoods.getChildOrderId().intValue());
//                取货方式0上门取件，1送货到店，2自行寄回
            if(leaseReturnGoodsMessage.size() > 0) {
                returnVo.setReturnType(leaseReturnGoodsMessage.get(0).getGetGoodsStyle().intValue());
            }
            List<OrderDetailGoodsVo> goodsList = backendOrderMapper.getOrderDetailPackageGoodsVos(orderGoodsId);
            goodsList.stream().forEach(q -> {
                List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
                String spec = "";
                if (CollectionUtils.isNotEmpty(specificationList)) {
                    for (LitemallGoodsProductSpecification specification : specificationList) {
                        spec += "," + specification.getInfoName() + ":" + specification.getName();
                    }
                }
                q.setGoodsSpec(spec.replaceFirst(",", ""));
            });
            returnVo.setGoodsList(goodsList);
            returnList.add(returnVo);
        }
        //发货时间
        if (packageList.size() > 0) {
            orderDetailVo.setDeliveryTime(packageList.get(0).getDeliveryTime());
        }
        //确认收货时间
        if (returnList.size() > 0) {
            List<OrderDetailDeliveryVo> stateList = returnList.get(returnList.size()-1).getStateList();
            if (stateList.size() > 0) {
                orderDetailVo.setConfirmReceiptTime(returnList.get(0).getStateList().get(stateList.size()-1).getDeliveryTime());
            }
        }

        orderDetailVo.setReturnList(returnList);
        return ResponseUtil.ok(orderDetailVo);
    }


    /**
     * 获取物流信息
     */
    public List<OrderDetailDeliveryVo> getLogistInfo(Integer baseInfoId) {
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue());
        List<OrderDetailDeliveryVo> backList = new ArrayList<>();
        List<OrderDetailDeliveryVo> orderDetailDeliveryVoList = new ArrayList<>(3);
        //System.out.println("===========>"+agedmallLgBaseInfo.getLgIsOver());
        //包裹未取消才会有物流信息
        if (!(LgBaseInfoIsOverEnum.CANCEL.getCode().equals(agedmallLgBaseInfo.getLgIsOver()))) {
            List<SaleLogisticsDto> logisticsMessage = appOrderMapper.getOneLogisticsMessage(baseInfoId);

            boolean isThird = false;
            AgedmallLgThirdLogisRecord lgThirdLogisRecord = new AgedmallLgThirdLogisRecord();
            for (SaleLogisticsDto saleLogisticsDto : logisticsMessage) {
                if (saleLogisticsDto.getLgExecType() == 2 && saleLogisticsDto.getType() == 2 && saleLogisticsDto.getBusiStat() == 1) {
                    isThird = true;
                    AgedmallLgThirdLogisRecordExample recordExample = new AgedmallLgThirdLogisRecordExample();
                    recordExample.createCriteria().andLgBusiIdEqualTo(saleLogisticsDto.getId().longValue());
                    lgThirdLogisRecord = agedmallLgThirdLogisRecordMapper.selectOneByExample(recordExample);
                }
            }

            for (int i = 0; i < logisticsMessage.size(); i++) {
                OrderDetailDeliveryVo orderDetailDeliveryVo = new OrderDetailDeliveryVo();
                orderDetailDeliveryVo.setDeliveryTime(logisticsMessage.get(i).getCreatedTime());
                //第三方物流
                if (isThird) {
                    orderDetailDeliveryVo.setDeliveryState("已交付第三方物流:" + lgThirdLogisRecord.getThirdLogisName() + "  单号为:" + lgThirdLogisRecord.getThirdOrderCode());
                } else {
                    orderDetailDeliveryVo.setDeliveryState(concatDesc(logisticsMessage.get(i).getLgType(), logisticsMessage.get(i).getType(), logisticsMessage.get(i).getBusiStat(),
                            logisticsMessage.get(i).getUserName(), logisticsMessage.get(i).getPhone()));
                }
                backList.add(orderDetailDeliveryVo);
            }
            //物流信息顺序排序并返回
            orderDetailDeliveryVoList = backList.stream().sorted((o1, o2) -> {
                LocalDateTime deliveryTime = o1.getDeliveryTime();
                LocalDateTime localDateTime = o2.getDeliveryTime();
                return deliveryTime.compareTo(localDateTime);
            }).collect(Collectors.toList());
        }
        return orderDetailDeliveryVoList;
    }


    public String concatDesc(Integer lgType, Integer type, Integer busiStat, String userName, String phone) {


        switch (lgType) {
            case 1:
                switch (type) {
                    case 1:
                        switch (busiStat) {
                            case 1:
                                return "正在配货中。。。";
                            case 2:
                                return "配货完成";
                            default:
                                return "";
                        }
                    case 2:
                        switch (busiStat) {
                            case 1:
                                return "正在配送中。。。配送员：" + userName + "   " + phone;
                            case 2:
                                return "配送完成";
                            default:
                                return "";
                        }
                    default:
                        return "";
                }
//            case 2:
//                switch (type){
//                    case 3:
//                        switch (busiStat){
//                            case 1:
//                                return "维护中";
//                            case 2:
//                                return "维护完成";
//                            default:
//                                return "";
//                        }
//                    default:
//                        return "";
//                }
            case 3:
                switch (type) {
                    case 4:
                        switch (busiStat) {
                            case 1:
                                return "归还中";
                            case 2:
                                return "归还完成";
                            default:
                                return "";
                        }
                    default:
                        return "";
                }
            case 4:
                switch (type) {
                    case 1:
                        switch (busiStat) {
                            case 1:
                                return "正在配货中。。。";
                            case 2:
                                return "配货完成";
                            default:
                                return "";
                        }
                    case 2:
                        switch (busiStat) {
                            case 1:
                                return "正在配送中。。。配送员：" + userName + "   " + phone;
                            case 2:
                                return "配送完成";
                            default:
                                return "";
                        }
                    case 4:
                        switch (busiStat) {
                            case 1:
                                return "退货中";
                            case 2:
                                return "退货完成";
                            default:
                                return "";
                        }
                    default:
                        return "";
                }
            case 5:
                switch (type) {
                    case 4:
                        switch (busiStat) {
                            case 1:
                                return "退货中";
                            case 2:
                                return "退货完成";
                            default:
                                return "";
                        }
                    default:
                        return "";
                }
            case 8:
                switch (type) {
                    case 8:
                        switch (busiStat) {
                            case 1:
                                return "正在配货中。。。" + userName + "   " + phone;
                            case 2:
                                return "已配货完成，等待用户自提。。。";
                            case 3:
                                return "自提完成";
                            default:
                                return "";
                        }
                    default:
                        return "";
                }
            default:
                return "";
        }
    }

    /**
     * ****************
     *
     * @param orderId 子订单id
     * @param packId  包裹的id 86
     * @return
     */
    public Object notDeliverLoad(Integer orderId, Integer packId) {
        OrderNotDeliverLoadVo orderNotDeliverLoadVo = new OrderNotDeliverLoadVo();
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        litemallOrderExample.or().andIdEqualTo(litemallOrderItem.getParentId());
        List<LitemallOrder> litemallOrders = litemallOrderMapper.selectByExample(litemallOrderExample);
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(litemallOrderItem.getId().longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);

        List<Integer> packageIdList = new ArrayList<>(10);
        for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsList) {
            if (null != litemallOrderGoods.getPackageId()) {
                packageIdList.add(litemallOrderGoods.getPackageId());
            }
        }

        if (litemallOrders.size() > 0) {
            orderNotDeliverLoadVo.setReceiverName(litemallOrders.get(0).getConsignee());
            orderNotDeliverLoadVo.setReceiverPhone(litemallOrders.get(0).getMobile());
            orderNotDeliverLoadVo.setReceiverAddress(litemallOrders.get(0).getAddressDetail());
        }
        //存放包裹里商品的 orderGoodsId  用于前端商品的是否选中
        List<Integer> orderGoodsIdList = new ArrayList<>(5);
        if (null != packId) {
            AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(packId.longValue());
            LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());
            List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
            for (LogisticsGoodsData logisticsGoodsData : goodsDataList) {
                orderGoodsIdList.add(logisticsGoodsData.getOrderGoodsId());
            }

            LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(goodsDataList.get(0).getOrderGoodsId());
            orderNotDeliverLoadVo.setStoreId(litemallOrderGoods.getStoreId().toString());

            if ("".equals(agedmallLgBaseInfo.getLgUserConf())) {
                orderNotDeliverLoadVo.setPackId(agedmallLgBaseInfo.getId().intValue());
                LogisticsStoreCloudData storeCloudData = commonData.getStoreCloudData();

                //配送员的id
                //门店或者物流
                if (("self").equals(litemallOrderItem.getDeliverySn())) {
                    //自提
                    orderNotDeliverLoadVo.setDeliveryOrSelf(0);
                } else if (("normal").equals(litemallOrderItem.getDeliverySn())) {
                    //配送
                    orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                    //门店
                    if (StringUtils.isNotBlank(storeCloudData.getLogisticsName())) {
                        orderNotDeliverLoadVo.setPackUserId("all");
                        orderNotDeliverLoadVo.setDeliveryUserId("all");
                        orderNotDeliverLoadVo.setDeliveryType(DeliveryTypeEnum.STORE.getCode());
                    } else {
                        //物流
                        orderNotDeliverLoadVo.setPackUserId("all");
                        orderNotDeliverLoadVo.setDeliveryType(DeliveryTypeEnum.LOGISTICS.getCode());
                    }
                } else {
                    //配送
                    orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                }
            } else if (null != agedmallLgBaseInfo.getLgUserConf()) {
                String lgUserConf = agedmallLgBaseInfo.getLgUserConf();
                List<LgData> lgDataList = JSON.parseArray(lgUserConf, LgData.class);
                //配货
                //packUserId 	配货员id
                String packUserId = lgDataList.get(0).getReceiveOrderMode();
                if ("all".equals(packUserId)) {
                    orderNotDeliverLoadVo.setPackUserId("all");
                } else if ("sort".equals(packUserId)) {
                    orderNotDeliverLoadVo.setPackUserId("sort");
                } else {
                    orderNotDeliverLoadVo.setPackUserId(lgDataList.get(0).getLgDataUser().getUid().toString());
                }
                //非自提
                if (lgDataList.size() > 1) {

                    //普通配送
                    orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                    //门店
                    orderNotDeliverLoadVo.setDeliveryType(1);

                    //门店配送 或者 物流配送
                    //物流配送
                    if ("third".equals(lgDataList.get(1).getLgMode())) {
                        orderNotDeliverLoadVo.setDeliveryUserId("");
                        //发货快递公司名称
                        orderNotDeliverLoadVo.setShipChannel(lgDataList.get(1).getLgDateThird().getCompany());
                        //快递单号
                        orderNotDeliverLoadVo.setShipSn(lgDataList.get(1).getLgDateThird().getLgOrderCode());

                        //deliveryUserId 	配送员id
                        //orderNotDeliverLoadVo.setDeliveryUserId(lgDataList.get(1).getLgDataUser().getUid());
                        //物流
                        orderNotDeliverLoadVo.setDeliveryType(2);
                        //普通配货
                        orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                    } else {
                        //门店配送
                        String deliveryUserId = lgDataList.get(1).getReceiveOrderMode();
                        if ("all".equals(deliveryUserId)) {
                            orderNotDeliverLoadVo.setDeliveryUserId("all");
                        } else if ("sort".equals(deliveryUserId)) {
                            orderNotDeliverLoadVo.setDeliveryUserId("sort");
                        } else {
                            // System.out.println("======"+lgDataList.get(1).getLgDataUser().getUid().toString());
                            orderNotDeliverLoadVo.setDeliveryUserId(lgDataList.get(1).getLgDataUser().getUid().toString());
                        }
                        //门店
                        orderNotDeliverLoadVo.setDeliveryType(1);
                        //普通配货
                        orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                    }
                } else {
                    //自提
                    orderNotDeliverLoadVo.setDeliveryOrSelf(0);

                }
            } else {
                //配送员的id
                //门店或者物流
                if (("self").equals(litemallOrderItem.getDeliverySn())) {
                    //自提
                    orderNotDeliverLoadVo.setDeliveryOrSelf(0);
                    System.out.println("====>" + orderNotDeliverLoadVo.getDeliveryOrSelf());
                } else if (("normal").equals(litemallOrderItem.getDeliverySn())) {
                    //配送
                    orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                } else {
                    //配送
                    orderNotDeliverLoadVo.setDeliveryOrSelf(1);
                    System.out.println("====>" + orderNotDeliverLoadVo.getDeliveryOrSelf());
                }
            }
        }
        List<OrderDeliveryGoodsVo> deliveryGoodsVos = backendOrderMapper.getOrderDeliveryGoodsVos(orderId, packId);
        deliveryGoodsVos.stream().forEach(q -> {
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
            //门店的id
            orderNotDeliverLoadVo.setStoreId(q.getStoreId().toString());
        });
        if (packageIdList.size() == litemallOrderGoodsList.size()) {
            //0未全部打包  1全部打包
            orderNotDeliverLoadVo.setAllPackage(1);
        } else {
            orderNotDeliverLoadVo.setAllPackage(0);
        }
        //System.out.println("======>"+orderNotDeliverLoadVo.getAllPackage());
        if (orderGoodsIdList.size() > 0) {
            orderNotDeliverLoadVo.setOrderGoodsIdList(orderGoodsIdList);
        }
        orderNotDeliverLoadVo.setOrderGoodsList(deliveryGoodsVos);

        return ResponseUtil.ok(orderNotDeliverLoadVo);
    }

    /**
     * 配货配送配置
     * @param orderId 子订单id
     * @param packId  物流基本信息id
     * @param deliveryType 发货方式 1门店 2 物流 3自提
     * @param deliveryUserId 配送员id （id为all为全部一起抢单，id为sort为按顺序抢单，其他数字为具体的配送员id）
     * @param shipChannel
     * @param shipSn
     * @param packUserId   配货员id （id为all为全部一起抢单，id为sort为按顺序抢单，其他数字为具体的配货员id）
     * @param isPickUpSelf 是否自提 0表示自提1表示非自提
     * @return
     */
    @Transactional
    public Object notDeliverSureDelivery(Integer orderId, String packId,
                                         Integer deliveryType, String deliveryUserId, String shipChannel, String shipSn, String packUserId, int isPickUpSelf) throws CheckException {
        //修改时传入
        //修改更新
        //存放处理好的订单商品表的id
        //通过packid获取包裹的信息
        List<Integer> orderGoodsIds = new ArrayList<>();
        String processState = "";

        //配货基本信息处理
        AgedmallLgBaseInfo agedmallLgBaseInfo = null;
        if (StringUtils.isBlank(packId)) {
            LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
            agedmallLgBaseInfo = logisticBusiBaseServiceImpl.createLgBaseInfoByOrderItem(null, orderItem, null, LgBaseInfoLgType.PURCHASING.getCode(), LgBaseInfoStatConstant.BUY_UN_ALLOT);
            String orderCode = orderItem.getOrderCode();
            Long baseInfoId = agedmallLgBaseInfo.getId();
            //配货
            logisticBusiBaseServiceImpl.userCreateOrderEventByManual(orderCode, baseInfoId.intValue(), LgBaseInfoLgType.PURCHASING.getCode(), true, packUserId);
            processState = ProcessStateConstant.PACKAGE_STATE_DISTRIBUTION;
        }else {
            AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
            agedmallLgBaseInfoExample.or().andIdEqualTo(Long.valueOf(packId));
            List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
            agedmallLgBaseInfo = agedmallLgBaseInfoList.get(0);
            Long baseInfoId = agedmallLgBaseInfo.getId();
            AgedmallLgMission mission = agedmallLgMissionService.getMissionByBaseInfoId(baseInfoId.intValue(), LogisticsMissionTypeEnum.ALLOT.getCode());
            if(mission == null) {
                //配货任务不存在，进行配货通知处理
                LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
                String orderCode = orderItem.getOrderCode();
                logisticBusiBaseServiceImpl.userCreateOrderEventByManual(orderCode, baseInfoId.intValue(), LgBaseInfoLgType.PURCHASING.getCode(), true, packUserId);
                processState = ProcessStateConstant.PACKAGE_STATE_DISTRIBUTION;
            }
        }

        //配送业务处理
        int lgBaseInfoId = agedmallLgBaseInfo.getId().intValue();
        if(deliveryType != null && deliveryType == 2) {
            processState = StringUtils.isBlank(processState) ? ProcessStateConstant.PACKAGE_STATE_DELIVER : processState;
            //物流配送
            logisticBusiBaseServiceImpl.deliverByThirdLogistic(lgBaseInfoId, shipSn, shipChannel, true);
        }else if (isPickUpSelf == 0) {
            //自提不会传 orderGoodsId 自提默认子订单下所有商品一并打包
            processState = StringUtils.isBlank(processState) ? ProcessStateConstant.PACKAGE_STATE_PICKUP : processState;
            LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
            String bigOrderCode = orderItem.getOrderCode();
            AgedmallLgBaseInfo autoGetBaseInfo = agedmallLgBaseInfoService.getBaseInfoByOrderCode(bigOrderCode, LgBaseInfoLgType.SELFPICKUP.getCode());
            if(autoGetBaseInfo == null) {
                autoGetBaseInfo = logisticBusiBaseServiceImpl.createLgBaseInfoByOrderItem(null, orderItem, null, LgBaseInfoLgType.SELFPICKUP.getCode(), LgBaseInfoStatConstant.PICK_UP_ALLOTING);
                Long baseInfId = autoGetBaseInfo.getId();
                logisticBusiBaseServiceImpl.userCreateOrderEvent(bigOrderCode, baseInfId.intValue(), LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode());
            }else {
                //自提配货任务是否已下发，已下发则不做处理
                Long baseInfId = autoGetBaseInfo.getId();
                AgedmallLgMission mission = agedmallLgMissionService.getMissionByBaseInfoId(baseInfId.intValue(), LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode());
                if(mission == null) {
                    //未下发任务，则重新下发自提配货任务
                    logisticBusiBaseServiceImpl.userCreateOrderEvent(bigOrderCode, baseInfId.intValue(), LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode());
                }
            }
        } else {
            processState = StringUtils.isBlank(processState) ? ProcessStateConstant.PACKAGE_STATE_DELIVER : processState;
            if(StringUtils.isNotBlank(deliveryUserId) && StringUtils.isNumeric(deliveryUserId)) {
                logisticBusiBaseServiceImpl.deliverBySelUser(lgBaseInfoId, Long.parseLong(deliveryUserId), true);
            }else {
                AgedmallLgMissionExample missionExample = new AgedmallLgMissionExample();
                missionExample.createCriteria().andBaseInfoIdEqualTo(lgBaseInfoId).andTypeEqualTo(LogisticsMissionTypeEnum.ALLOT.getCode());
                List<AgedmallLgMission> lgMissionList = agedmallLgMissionMapper.selectByExample(missionExample);
                AgedmallLgMission lgDeployMission = lgMissionList.get(lgMissionList.size() - 1);
                //创建任务并发送接单信息
                logisticBusiBaseServiceImpl.deliverBySortOrAll(lgBaseInfoId, lgDeployMission.getType(), true);
            }
        }

        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());
        List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
        for (LogisticsGoodsData logisticsGoodsData : goodsDataList) {
            orderGoodsIds.add(logisticsGoodsData.getOrderGoodsId());
        }
        //更新litemallOrdergoods 包裹id
        backendOrderMapper.setOrderGoodsPackageId(orderGoodsIds, lgBaseInfoId);
        // 添加包裹状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_SHIP, lgBaseInfoId, processState);
        return ResponseUtil.ok();
    }


    /**
     * 待付款和未发货的情况下可以取消订单
     *
     * @param id 子订单id
     * @return
     */
    public Object cancleOrder(@RequestParam Integer id) {
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(id);
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        litemallOrderExample.or().andIdEqualTo(litemallOrderItem.getParentId());
        LitemallOrder order = litemallOrderMapper.selectOneByExampleSelective(litemallOrderExample);
        // order = litemallOrderMapper.selectByPrimaryKey(id);
        if (null == order) {
            return ResponseUtil.badArgumentValue();
        }
        OrderHandleOption orderHandleOption = OrderUtil.build(order);
        if (!orderHandleOption.isCancel()) {
            return ResponseUtil.fail("订单不能取消");
        }
        //订单已付款 但是未发货 可以取消 退货退款
        if (!orderHandleOption.isRemind()) {
            return ResponseUtil.fail("订单不能取消");
        }
        order.setOrderStatus(OrderUtil.STATUS_CANCEL);
        order.setUpdateTime(LocalDateTime.now());
        litemallOrderMapper.updateByPrimaryKeySelective(order);

        //更新服务订单
        AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
        serviceOrderExample.createCriteria().andDeletedEqualTo(false)
                .andOrderIdEqualTo(order.getId().longValue());
        AgedmallServiceOrder serviceOrder = new AgedmallServiceOrder();
        serviceOrder.setStat(ServiceOrderConstant.STATUS_CANCEL);
        agedmallServiceOrderMapper.updateByExampleSelective(serviceOrder, serviceOrderExample);

        //更新子订单信息
        LitemallOrderItemExample litemallOrderItemExample = new LitemallOrderItemExample();
        litemallOrderItemExample.createCriteria().andDeletedEqualTo(false)
                .andParentIdEqualTo(order.getId());
        List<LitemallOrderItem> subOrderList = litemallOrderItemMapper.selectByExample(litemallOrderItemExample);

        for (LitemallOrderItem orderItem : subOrderList) {
            // 更新子订单状态
            orderItem.setOrderStatus(OrderUtil.STATUS_CANCEL);
            orderItem.setUpdateTime(LocalDateTime.now());
            litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);

            LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
            litemallOrderGoodsExample.createCriteria().andDeletedEqualTo(false)
                    .andOrderIdEqualTo(orderItem.getId());
            List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                // 还原库存数量 服务没有库存概念
                if (!OrderGoodsConstant.TYPE_EXTEND.equals(orderGoods.getType())) {
                    Integer productId = orderGoods.getProductId();
                    Short number = orderGoods.getNumber();
                    goodsProductMapper.addStock(productId, number);
                }

                if (StringUtils.isNotEmpty(orderGoods.getRfid())) {
                    List<String> rfidList = Arrays.asList(orderGoods.getRfid().split(","));
                    // 取消rfid锁定
                    if (InventoryUtil.STOCK_SOFTCHAIN.equals(orderGoods.getStockType())) {
                        UnLockGoodsVo unLockGoodsVo = new UnLockGoodsVo();
                        unLockGoodsVo.setRfid(rfidList);
                        int type=0;
                        //        如果为到院自提
                        AgedmallHospitalSendSelfLocation selfLocation = null;
                        if(orderGoods.getHospitalSelfLocationId()!=null){
                            selfLocation = agedmallHospitalSendSelfLocationMapper.selectByPrimaryKey(orderGoods.getHospitalSelfLocationId());
                        }
                        if(ObjectUtil.isNotNull(selfLocation)&&selfLocation.getInventoryFlag()==0){
                            type=2;
                        }
                        unLockGoodsVo.setType(type);
                        lockRfidUtil.unlockGoods(unLockGoodsVo);
                    }
                    if (InventoryUtil.STOCK_CABINET.equals(orderGoods.getStockType())) {
                        UnLockCabinetGoodsVo unLockCabinetGoodsVo = new UnLockCabinetGoodsVo();
                        unLockCabinetGoodsVo.setRfid(rfidList);
                        lockRfidUtil.unlockCabinetGoods(unLockCabinetGoodsVo);
                    }
                }
            }

            //获取包裹信息
            AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
            agedmallLgBaseInfoExample.or().andOrderCodeEqualTo(order.getOrderSn());
            List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);

            if (agedmallLgBaseInfoList.size() > 0) {
                //更改包裹的信息
                AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
                agedmallLgBaseInfo.setOrderCode(order.getOrderSn());
                agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
                agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.CANCEL.getCode());
                agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
            }
        }
        //退款
        //订单已付款 但是未发货 可以取消 退货退款
        if (orderHandleOption.isRemind()) {
            leaseOrderService.orderSettlement(litemallOrderItem.getOrderCode(), litemallOrderItem.getChildOrderCode());
        }
        return ResponseUtil.ok();
    }

    public Object notTakingByselfLoad(@RequestParam Integer orderId) {
        OrderNotDeliverLoadVo orderNotDeliverLoadVo = new OrderNotDeliverLoadVo();
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(orderId);
        if (null != litemallOrder) {
            orderNotDeliverLoadVo.setReceiverName(litemallOrder.getConsignee());
            orderNotDeliverLoadVo.setReceiverPhone(litemallOrder.getMobile());
            orderNotDeliverLoadVo.setReceiverAddress(litemallOrder.getAddressDetail());
        }

        List<OrderDeliveryGoodsVo> deliveryGoodsVos = backendOrderMapper.getSelfPickupGoodsVos(orderId);
        deliveryGoodsVos.stream().forEach(q -> q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue())));
        orderNotDeliverLoadVo.setOrderGoodsList(deliveryGoodsVos);

        return ResponseUtil.ok(orderNotDeliverLoadVo);
    }

    /**
     * 确认收货
     * @param ids 子订单id列表
     * @return
     */
    @Transactional
    public Object notTakingByselfTaked(List<Integer> ids) {
        try {
            orderService.confirmReceiptSelf(ids);
        } catch (AgedmallException e) {
            return ResponseUtil.fail(e.getCode(), e.getMsg());
        }
        return ResponseUtil.ok();
    }

    @Transactional
    public Object notTakeTaked(Integer id) {
        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        agedmallLgBaseInfoExample.or().andIdEqualTo(id.longValue());
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfoList.get(0).getLgContent());
        Integer orderGoodsId = commonData.getGoodsDataList().get(0).getOrderGoodsId();
        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        LitemallOrderItemExample litemallOrderItemExample = new LitemallOrderItemExample();
        litemallOrderItemExample.or().andIdEqualTo(litemallOrderGoods.getChildOrderId().intValue());
        LitemallOrderItem orderItem = litemallOrderItemMapper.selectOneByExample(litemallOrderItemExample);
        String bigOrderSn = commonData.getOrderData().getBigOrderSn();
        //判断物流是否完成 未完成不能收货
        boolean isFinishSubOrderLogistics = isFinishSubOrderLogistics(bigOrderSn, litemallOrderGoods.getChildOrderId().intValue());

        //获取订单状态       当status == 301 || status == 302才能确认收货
        OrderHandleOption orderHandleOption = OrderUtil.buildItem(orderItem);
        //isConfirm 为true才能确认收货
        if (!orderHandleOption.isConfirm()) {
            throw new cn.com.ejiakanghu.core.exceptions.BizException("订单不能确认收货");
        }
        if (!isFinishSubOrderLogistics) {
            throw new cn.com.ejiakanghu.core.exceptions.BizException("商品正在配送中，无法收货");
        }

        AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
        agedmallLgBaseInfo.setId(id.longValue());
        agedmallLgBaseInfo.setLgIsOver(1);
        agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        updateOrderState(id);
        // 添加包裹状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_SHIP, id, ProcessStateConstant.PACKAGE_STATE_SIGN);
        return ResponseUtil.ok();
    }

    // 包裹收到后 查看是否所有包裹都收到，都确认收货 售卖订单完成，租赁订单使用中
    private void updateOrderState(Integer packageId) {
        // 根据包裹查子订单
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.createCriteria().andDeletedEqualTo(false)
                .andPackageIdEqualTo(packageId);
        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectOneByExample(litemallOrderGoodsExample);
        // 查询子订单下 未确认收货商品，没有的话 修改状态                                     大订单id
        int unConfirmCount = backendOrderMapper.getUnConfirmCount(litemallOrderGoods.getOrderId());
        //没有未收货的商品
        if (unConfirmCount == 0) {
            LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
            orderItemExample.createCriteria().andChildOrderCodeEqualTo(litemallOrderGoods.getChildOrderCode()).andOrderCodeEqualTo(litemallOrderGoods.getOrderCode());
            LitemallOrderItem orderItem = litemallOrderItemMapper.selectOneByExample(orderItemExample);
            //租赁商品
            if (GoodsConstant.GOODS_TYPE_LEASE.equals(orderItem.getGoodsType())) {
                orderItem.setOrderStatus(OrderUtil.STATUS_LEASE_CONFIRM);
                orderItem.setExtractTime(LocalDateTime.now());
            } else {
                orderItem.setOrderStatus(OrderUtil.STATUS_CONFIRM);
                litemallOrderService.saveSettle(orderItem, null);
                litemallOrderService.saveDeduct(orderItem);
                //orderItem.setFinishTime(LocalDateTime.now());
                orderItem.setShipArriveTime(LocalDateTime.now());
                // 取消订单超时未确认任务
//                taskService.removeTask(new OrderUnconfirmTask(order.getId()));
            }
            orderItem.setConfirmTime(LocalDateTime.now());
            litemallOrderService.updateItem(orderItem);
            orderItem.setConfirmTime(LocalDateTime.now());
            litemallOrderService.updateItem(orderItem);
            //判断是否有商品，更新rfid状态
            orderStateService.confirmOrderRfidStateChange(orderItem);
            //更新签收表
            logisticBusiBaseServiceImpl.insertSignInConfirm(orderItem.getOrderCode(), orderItem.getChildOrderCode(), orderItem.getUserId());
        }
    }

    public Object notTakeReturnLoad(Integer orderId) {
        List<OrderDeliveryGoodsVo> deliveryGoodsVos = backendOrderMapper.getAfterSaleGoodsVos(orderId);
        deliveryGoodsVos.stream().forEach(q -> {
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
        });
        return ResponseUtil.ok(deliveryGoodsVos);
    }


    public Object notTakeReturn(NotTakeReturnForm notTakeReturnForm) {
        List<Integer> orderGoodsIdsList = new ArrayList<>(5);
        String orderGoodsIds = notTakeReturnForm.getOrderGoodsIds();
        if(StringUtils.isBlank(orderGoodsIds)) {
            return null;
        }
        String[] orderGoodsIdsArr = orderGoodsIds.split(",");
        for (String orderGoodsId : orderGoodsIdsArr) {
            orderGoodsIdsList.add(Integer.parseInt(orderGoodsId));
        }

        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsIdsList.get(0));
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(litemallOrderGoods.getOrderId());
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(notTakeReturnForm.getId());

        UserAddressInfo userAddressInfo = new UserAddressInfo();
        userAddressInfo.setDetail(litemallOrder.getAddressDetail());
        userAddressInfo.setProvince(litemallOrder.getProvince());
        userAddressInfo.setCity(litemallOrder.getCity());
        userAddressInfo.setAddress(litemallOrder.getAddress());
        userAddressInfo.setUserName(litemallOrder.getConsignee());
        userAddressInfo.setHosId(litemallOrder.getHospitalId());
        userAddressInfo.setHosName(litemallOrder.getHospitalName());
        userAddressInfo.setLat(litemallOrder.getLat());
        userAddressInfo.setLng(litemallOrder.getLng());
        userAddressInfo.setPhone(litemallOrder.getMobile());
        userAddressInfo.setVillage(litemallOrder.getCounty());

        //商品退还状态 0退款 1退货退款 2换货
        int state = notTakeReturnForm.getState();
        //仅退款
        //1.将费用原路退回用户
        //2.将订单状态改为已退款
        //3.记录退款的操作记录
        //4.租赁商品和售卖商品有什么区别
        if (state == 0) {
            //进行退款处理
            leaseOrderService.orderSettlementRefund(litemallOrder.getOrderSn(), litemallOrderItem.getChildOrderCode());
            LitemallOrderItem litemallOrderItemUpdate = litemallOrderItemMapper.selectByPrimaryKey(notTakeReturnForm.getId());
            litemallOrderItemUpdate.setUpdateTime(LocalDateTime.now());
            litemallOrderItemUpdate.setOrderStatus(OrderUtil.STATUS_REFUND);
            litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItemUpdate);
        } else if (state == 1) {

            /**
             * 退货退款   可以选择门店或者是物流退货
             * 门店退款
             *     packMainId 必传 ship 1
             *     expressCompany "" expressCode ""   维护人员  取货人员
             * 物流退款
             *      packMainId ”“  ship 2
             *      必传 有值
             *      expressCompany "" expressCode ""   维护人员   maintain
             *
             */
            //退货退款
            if (DeliveryTypeEnum.STORE.getCode().equals(notTakeReturnForm.getShip())) {
                packageLogistics(notTakeReturnForm.getDeliveryManId(), notTakeReturnForm.getMaintainId(), notTakeReturnForm.getShip(), notTakeReturnForm.getId(), orderGoodsIdsList, LgBaseInfoStatConstant.BACKING_GOODS, LgBaseInfoLgType.RETURNTHEGOODS.getCode(), notTakeReturnForm.getExpressCompany(), notTakeReturnForm.getExpressCode(), "退货", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
            } else {
                packageLogistics("", notTakeReturnForm.getMaintainId(), notTakeReturnForm.getShip(), notTakeReturnForm.getId(), orderGoodsIdsList, LgBaseInfoStatConstant.BACKING_GOODS, LgBaseInfoLgType.RETURNTHEGOODS.getCode(), notTakeReturnForm.getExpressCompany(), notTakeReturnForm.getExpressCode(), "", "退货", LogisticsMissionTypeEnum.RETURN.getCode(), null, "");
            }

            //boolean finishSubOrderLogistics = isFinishSubOrderLogistics(litemallOrder.getOrderSn(), Integer.parseInt(litemallOrderItem.getChildOrderCode()));
            //物流完成
            litemallOrderItem.setOrderStatus(OrderUtil.showType(OrderUtil.STATUS_AUTO_CANCEL.shortValue()).shortValue());
            litemallOrderItem.setId(notTakeReturnForm.getId());
            litemallOrderItem.setUpdateTime(LocalDateTime.now());
            //litemallOrderItem.setOrderStatus(showType(Short orderStatus));
            litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
            //计算金额
            //leaseOrderService.orderSettlementRefund(orderGoodsIdsList, litemallOrder.getOrderSn(), litemallOrderItem.getChildOrderCode());
            //leaseOrderService.orderSettlement(litemallOrder.getOrderSn(), litemallOrderItem.getChildOrderCode());

        }
        //换货
        //换货  取货
        //换货  配货
        //换货  配送
        /**
         * 换货   可以选择门店或者是物流换货  取货->配货->发货->维护  取货->维护 取货完成->配货->发货
         * 门店配货 配送
         *     packMainId 必传 ship 1
         *     expressCompany "" expressCode ""
         * 物流 配送
         *      packMainId ”“  ship 2
         *      必传 有值
         *      expressCompany "" expressCode ""
         */
        else {

            for (Integer orderGoodsId : orderGoodsIdsList) {
                LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
                LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(orderGoods.getOrderId());
                // 添加售后表
                LitemallAftersale litemallAftersale = insertAfterSale(order.getUserId(), order.getId(), orderGoods.getId(), notTakeReturnForm.getState(), notTakeReturnForm.getReason(), orderGoods.getPrice());
                // 添加归还表
                insertReturnRecord(litemallAftersale.getId(), order.getUserId().longValue(), order.getOrderSn(), notTakeReturnForm.getState().byteValue(),
                        orderGoodsId, orderGoods.getPrice(), notTakeReturnForm.getShip(), "sort".equals(notTakeReturnForm.getDeliveryManId()) ? 1 : "all".equals(notTakeReturnForm.getDeliveryManId()) ? 0 : Integer.parseInt(notTakeReturnForm.getDeliveryManId()), userAddressInfo, notTakeReturnForm.getExpressCompany(), notTakeReturnForm.getExpressCode());
            }


            if (DeliveryTypeEnum.STORE.getCode().equals(notTakeReturnForm.getShip())) {
                //门店
                packageLogistics(notTakeReturnForm.getDeliveryManId(), notTakeReturnForm.getPackUserid(), notTakeReturnForm.getShip(), notTakeReturnForm.getId(), orderGoodsIdsList, LgBaseInfoStatConstant.CHANGE_ALLOTING, LgBaseInfoLgType.EXCHANGE.getCode(), notTakeReturnForm.getExpressCompany(), notTakeReturnForm.getExpressCode(), "配货", "配送", LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode(), LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode(), notTakeReturnForm.getMaintainId());
                //packageLogistics(packUserid, maintainId, ship, id, orderGoodsIds, LgBaseInfoStatConstant.CHANGE_BACKING_GOODS, LgBaseInfoLgType.EXCHANGE.getCode(), expressCompany, expressCode, "取货", "维护", LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
            } else {
                //物流
                packageLogistics("", notTakeReturnForm.getPackUserid(), notTakeReturnForm.getShip(), notTakeReturnForm.getId(), orderGoodsIdsList, LgBaseInfoStatConstant.CHANGE_BACKING_GOODS, LgBaseInfoLgType.EXCHANGE.getCode(), notTakeReturnForm.getExpressCompany(), notTakeReturnForm.getExpressCode(), "配货", "维护", LogisticsMissionTypeEnum.ALLOT.getCode(), null, notTakeReturnForm.getMaintainId());
            }


        }
        return ResponseUtil.ok();
    }


    // 添加售后表
    public LitemallAftersale insertAfterSale(Integer userId, Integer orderId, Integer orderGoodsId, Integer state, String reason, BigDecimal orderPrice) {
        LitemallAftersale aftersale = new LitemallAftersale();
        aftersale.setAftersaleSn(agedmallOrderSerialService.getAftersaleSn());
        aftersale.setUserId(userId);
        aftersale.setOrderId(orderId);
        aftersale.setOrderGoodsId(orderGoodsId);
        aftersale.setType(state.shortValue());
        aftersale.setReason(reason);
        aftersale.setStatus(AftersaleConstant.STATUS_PICK_UP);
        aftersale.setAmount(orderPrice);
        aftersale.setReceived(0 != state);
        aftersale.setHandleTime(LocalDateTime.now());
        aftersale.setAddTime(LocalDateTime.now());
        aftersale.setUpdateTime(LocalDateTime.now());
        litemallAftersaleMapper.insertSelective(aftersale);
        return aftersale;
    }

    //添加归还表
    public void insertReturnRecord(Integer aftersaleId, Long uid, String orderSn, byte state, Integer orderGoodsId, BigDecimal orderGoodsPrice, Integer ship,
                                   Integer deliveryManId, UserAddressInfo addressInfo, String expressCompany, String expressCode) {
        AgedmallReturnGoodsRecord returnGoodsRecord = new AgedmallReturnGoodsRecord();
        returnGoodsRecord.setAfterSaleId(aftersaleId);
        returnGoodsRecord.setUid(uid);
        returnGoodsRecord.setOrderCode(orderSn);
        returnGoodsRecord.setReturnType(state);
        returnGoodsRecord.setGoodsIds(orderGoodsId + "");
        returnGoodsRecord.setGetGoodsStyle(ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP);
        returnGoodsRecord.setPrice(orderGoodsPrice);
        returnGoodsRecord.setUpdoorType(ship);
        returnGoodsRecord.setDeliveryManId(deliveryManId);
        if (addressInfo != null) {
            String orderAddressDetail = JSON.toJSONString(addressInfo);
            returnGoodsRecord.setUserAddressInfo(orderAddressDetail);
        }
        returnGoodsRecord.setExpressName(expressCompany);
        returnGoodsRecord.setExpressCode(expressCode);
        returnGoodsRecord.setAddTime(LocalDateTime.now());
        returnGoodsRecord.setUpdateTime(LocalDateTime.now());
        agedmallReturnGoodsRecordMapper.insertSelective(returnGoodsRecord);
    }

    public Object usingReturnLoad(Integer orderId) {
        List<OrderDeliveryGoodsVo> deliveryGoodsVos = backendOrderMapper.getUsingGoodsVos(orderId);
        deliveryGoodsVos.stream().forEach(q -> {
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
        });
        return ResponseUtil.ok(deliveryGoodsVos);
    }

    /**
     * @param id             子订单id
     * @param orderIds       订单商品表 id
     * @param ship           归还方式 1配送员 2快递
     * @param deliveryManId
     * @param expressCompany
     * @param expressCode
     * @return
     */
    @Transactional
    public Object usingReturn(Integer id, List<Integer> orderIds, Integer ship,
                              String deliveryManId, String maintainIdManId, String expressCompany, String expressCode) {
        // 修改订单状态 选择物流公司商品状态变更为待商户收货，选择门店商品状态变更为待取货
        // 租赁订单只有一个   售卖商品可能会有多个
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(id);
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(id.longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(litemallOrderGoodsList.get(0).getOrderId());
        //更新大订单信息
        for (Integer orderId : orderIds) {
            //配送员
            if (ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP == ship.byteValue()) {
                litemallOrderService.updateStatus(litemallOrder.getId(), OrderUtil.STATUS_RETURN);
                //更新子订单信息
                litemallOrderService.updateLitemallOrderItem(id, OrderUtil.STATUS_RETURN);
                //更新订单商品表信息
                litemallOrderService.updateLitemallOrderGoods(orderId, OrderUtil.STATUS_RETURN);
                //物流
            } else if (ReturnGoodsRecordConstant.GET_GOODS_STYLE_SELF_EXPRESS == ship.byteValue()) {
                litemallOrderService.updateStatus(litemallOrder.getId(), OrderUtil.STATUS_RETURN_SELF);
                //更新子订单信息
                litemallOrderService.updateLitemallOrderItem(id, OrderUtil.STATUS_RETURN_SELF);
                //更新订单商品表信息
                litemallOrderService.updateLitemallOrderGoods(orderId, OrderUtil.STATUS_RETURN_SELF);
            }
        }

        //归还 门店配送 或者 三方物流
        if (DeliveryTypeEnum.STORE.getCode().equals(ship)) {
            packageLogistics(maintainIdManId, deliveryManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "归还", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        } else {
            packageLogistics("", maintainIdManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        }

        // 添加归还表
        AgedmallLeaseGoodsReturnRecord agedmallLeaseGoodsReturnRecord = new AgedmallLeaseGoodsReturnRecord();
        agedmallLeaseGoodsReturnRecord.setBigOrderId(litemallOrder.getId() + "");
        //agedmallLeaseGoodsReturnRecord.setSubOrderIds(StringUtils.join(id, ","));
        agedmallLeaseGoodsReturnRecord.setSubOrderIds(id.toString());
        agedmallLeaseGoodsReturnRecord.setGetGoodsStyle(ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP);
        agedmallLeaseGoodsReturnRecord.setUpdoorType(ship);
        agedmallLeaseGoodsReturnRecord.setUpdoorPrice(BigDecimal.ZERO);
        if (!"".equals(deliveryManId) && !"all".equals(deliveryManId) && !"sort".equals(deliveryManId)) {
            agedmallLeaseGoodsReturnRecord.setUpdoorManId(Integer.parseInt(deliveryManId));
        }
        agedmallLeaseGoodsReturnRecord.setExpressName(expressCompany);
        agedmallLeaseGoodsReturnRecord.setExpressCode(expressCode);
        agedmallLeaseGoodsReturnRecord.setAddTime(LocalDateTime.now());
        agedmallLeaseGoodsReturnRecord.setUpdateTime(LocalDateTime.now());
        agedmallLeaseGoodsReturnRecordMapper.insertSelective(agedmallLeaseGoodsReturnRecord);
        // 添加归还状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_RETURN, agedmallLeaseGoodsReturnRecord.getId(), ProcessStateConstant.RETURN_STATE_PICKUP);
        leaseOrderService.orderSettlement(litemallOrderItem.getOrderCode(), litemallOrderItem.getChildOrderCode());
        return ResponseUtil.ok();
    }

    /**
     * 更新子订单的状态和大订单的状态 以及更新 agedmall_cabinet  agedmall_lg_rfid_goods_cur_stat agedmall_rfid_goods_product agedmall_goods_equ
     * 计算买断的价格 计算金额
     *
     * @param orderBuyOutForm
     * @return
     */
    @Transactional
    public Object usingBuyOut(OrderBuyOutForm orderBuyOutForm) {
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(orderBuyOutForm.getId());
        List<OrderBuyOut> orderBuyOutList = orderBuyOutForm.getBuyOutList();
        LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(litemallOrderItem.getParentId());
        BigDecimal oneTotalPrice = BigDecimal.ZERO;
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal tempPrice;
        //计算买断总价格
        for (OrderBuyOut orderBuyOut : orderBuyOutList) {
            BigDecimal buyOutPrice = new BigDecimal(orderBuyOut.getAmount());
            tempPrice = oneTotalPrice.add(buyOutPrice);
            totalPrice = tempPrice.setScale(2, BigDecimal.ROUND_DOWN);
        }
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderBuyOutList.get(0).getGoodsId());
        litemallOrderExample.or().andIdEqualTo(litemallOrderGoods.getOrderId());
        LitemallOrder litemallOrder = litemallOrderMapper.selectOneByExample(litemallOrderExample);
        litemallOrder.setIsBuyout(1);
        litemallOrder.setBuyoutPrice(totalPrice);
        litemallOrder.setOrderStatus(OrderUtil.STATUS_RETURN_SETTLE);
        litemallOrderMapper.updateByPrimaryKeySelective(litemallOrder);

        for (OrderBuyOut orderBuyOut : orderBuyOutList) {
            LitemallOrderGoods litemallOrderGoodss = litemallOrderGoodsMapper.selectByPrimaryKey(orderBuyOut.getGoodsId());
            String rfids = litemallOrderGoodss.getRfid();
            Integer stockType = litemallOrderGoodss.getStockType();
            //链条锁 衣柜锁
            if (stockType.equals(1)) {
                String[] rfidArray = rfids.split(",");
                for (String rfid : rfidArray) {
                    AgedmallGoodsEquExample agedmallGoodsEquExample = new AgedmallGoodsEquExample();
                    agedmallGoodsEquExample.or().andEquIdEqualTo(Long.parseLong(rfid)).andTypeEqualTo(0);
                    AgedmallGoodsEqu agedmallGoodsEqu = agedmallGoodsEquMapper.selectOneByExample(agedmallGoodsEquExample);
                    //更新 商品设备信息表
                    agedmallGoodsEqu.setState(5);
                    agedmallGoodsEqu.setUpdateTime(LocalDateTime.now());
                    agedmallGoodsEqu.setDistributionType(4);
                    agedmallGoodsEquMapper.updateByPrimaryKeySelective(agedmallGoodsEqu);

                    //更新 rfid商品当前的状态信息表
                    AgedmallLgRfidGoodsCurStatExample agedmallLgRfidGoodsCurStatExample = new AgedmallLgRfidGoodsCurStatExample();
                    agedmallLgRfidGoodsCurStatExample.or().andRfidEqualTo(rfid);
                    AgedmallLgRfidGoodsCurStat agedmallLgRfidGoodsCurStat = agedmallLgRfidGoodsCurStatMapper.selectOneByExample(agedmallLgRfidGoodsCurStatExample);
                    //已售
                    agedmallLgRfidGoodsCurStat.setCurStat(9);
                    agedmallLgRfidGoodsCurStat.setUpdateTime(LocalDateTime.now());
                    agedmallLgRfidGoodsCurStatMapper.updateByPrimaryKeySelective(agedmallLgRfidGoodsCurStat);

                }
            } else if (stockType.equals(2)) {
                String[] rfidArray = rfids.split(",");
                for (String rfid : rfidArray) {
                    //衣柜-商品表
                    AgedmallCabinetGoodsExample agedmallCabinetGoodsExample = new AgedmallCabinetGoodsExample();
                    agedmallCabinetGoodsExample.or().andGoodsRfidIdEqualTo(Long.parseLong(rfid));
                    AgedmallCabinetGoods agedmallCabinetGoods = agedmallCabinetGoodsMapper.selectOneByExample(agedmallCabinetGoodsExample);
                    agedmallCabinetGoods.setUpdateTime(LocalDateTime.now());
                    //已售出
                    agedmallCabinetGoods.setStat(2);
                    agedmallCabinetGoodsMapper.updateByPrimaryKeySelective(agedmallCabinetGoods);

                    //更新 rfid商品当前的状态信息表
                    AgedmallLgRfidGoodsCurStatExample agedmallLgRfidGoodsCurStatExample = new AgedmallLgRfidGoodsCurStatExample();
                    agedmallLgRfidGoodsCurStatExample.or().andRfidEqualTo(rfid);
                    AgedmallLgRfidGoodsCurStat agedmallLgRfidGoodsCurStat = agedmallLgRfidGoodsCurStatMapper.selectOneByExample(agedmallLgRfidGoodsCurStatExample);
                    //已售
                    agedmallLgRfidGoodsCurStat.setCurStat(9);
                    agedmallLgRfidGoodsCurStat.setUpdateTime(LocalDateTime.now());
                    agedmallLgRfidGoodsCurStatMapper.updateByPrimaryKeySelective(agedmallLgRfidGoodsCurStat);

                    //更新rfid-商品规格关联表
                    AgedmallRfidGoodsProductExample agedmallRfidGoodsProductExample = new AgedmallRfidGoodsProductExample();
                    agedmallRfidGoodsProductExample.or().andRfidEqualTo(rfid);
                    AgedmallRfidGoodsProduct agedmallRfidGoodsProduct = agedmallRfidGoodsProductMapper.selectOneByExample(agedmallRfidGoodsProductExample);
                    agedmallRfidGoodsProduct.setStat(4);
                    agedmallRfidGoodsProduct.setUpdateTime(LocalDateTime.now());
                    agedmallRfidGoodsProductMapper.updateByPrimaryKeySelective(agedmallRfidGoodsProduct);
                }
            }
            //更新 litemallOrderGoods
            LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderBuyOut.getGoodsId());
            orderGoods.setUpdateTime(LocalDateTime.now());
            //交易完成
            orderGoods.setOrderGoodsStat(OrderUtil.STATUS_RETURN_SUCCESS.intValue());
            litemallOrderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
            //更新 litemallproduct
            //orderGoods.getProductId()
            LitemallGoodsProduct litemallGoodsProduct = litemallGoodsProductMapper.selectByPrimaryKey(orderGoods.getProductId());
            //TODO 库存减少
            //litemallGoodsProduct.setNumber(litemallGoodsProduct.getNumber() - orderBuyOut.getNumber());
            litemallGoodsProductMapper.updateByPrimaryKeySelective(litemallGoodsProduct);
            //更新 litemallgoods
            //goods_id
            LitemallGoods litemallGoods = litemallGoodsMapper.selectByPrimaryKey(orderGoods.getGoodsId());
            litemallGoods.setUpdateTime(LocalDateTime.now());
            litemallGoodsMapper.updateByPrimaryKeyWithBLOBs(litemallGoods);
        }

        /**
         * 买断
         * 退款  租金 + 抵扣金 - 费用 - 买断金额 > 0  租赁
         * 扣款  租金 + 抵扣金 - 费用 - 买断金额 < 0  租赁
         */
        AgedmallWxNodepositRecordExample agedmallWxNodepositRecordExample = new AgedmallWxNodepositRecordExample();
        agedmallWxNodepositRecordExample.or().andChildOrderCodeEqualTo(litemallOrderItem.getChildOrderCode());
        List<AgedmallWxNodepositRecord> agedmallWxNodepositRecords = agedmallWxNodepositRecordMapper.selectByExample(agedmallWxNodepositRecordExample);

        //非免押
        if (agedmallWxNodepositRecords.size() == 0) {
            leaseOrderService.buyOutorderSettlement(order.getOrderSn(), litemallOrderItem.getChildOrderCode(), totalPrice);
        } else {
            //免押
            //leaseOrderService.orderSettlement(order.getOrderSn(), litemallOrderItem.getChildOrderCode());

            leaseOrderService.BuyOutOrderSettlement(order.getOrderSn(), litemallOrderItem.getChildOrderCode(), totalPrice);

            //更新免押表
            AgedmallWxNodepositRecord agedmallWxNodepositRecord = new AgedmallWxNodepositRecord();
            agedmallWxNodepositRecord.setId(agedmallWxNodepositRecords.get(0).getId());
            agedmallWxNodepositRecord.setUpdated(LocalDateTime.now());
            agedmallWxNodepositRecord.setIsDeduct((byte) 1);
            agedmallWxNodepositRecord.setPayFee(totalPrice);
            agedmallWxNodepositRecordMapper.updateByPrimaryKeySelective(agedmallWxNodepositRecord);
        }


        return ResponseUtil.ok();
    }

    /**
     * @param orderId 子订单id
     * @return
     */
    public Object notPickUpLoad(Integer orderId) {

        NotPickUploadLoad notPickUploadLoad = new NotPickUploadLoad();
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        litemallOrderExample.or().andIdEqualTo(litemallOrderItem.getParentId());
        LitemallOrder litemallOrder = litemallOrderMapper.selectOneByExample(litemallOrderExample);
        notPickUploadLoad.setReceiverName(litemallOrder.getConsignee());
        notPickUploadLoad.setReceiverPhone(litemallOrder.getMobile());
        notPickUploadLoad.setReceiverAddress(litemallOrder.getAddress());
        List<OrderDeliveryGoodsVo> deliveryGoodsVos = backendOrderMapper.getPickupGoodsVos(orderId);
        deliveryGoodsVos.stream().forEach(q -> {
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
        });
        notPickUploadLoad.setDeliveryGoodsVos(deliveryGoodsVos);
        return ResponseUtil.ok(notPickUploadLoad);
    }

    /**
     * @param id             //子订单号
     * @param orderIds       商品订单表(litemall_order_goods)的主键id 多个逗号分隔
     * @param ship
     * @param deliveryManId  配送人员id
     * @param expressCompany
     * @param expressCode
     * @param maintainManId  维护人员id
     * @return
     */
    public Object notPickUpPickUp(Integer id, List<Integer> orderIds, Integer ship,
                                  String deliveryManId, String expressCompany, String expressCode, String maintainManId) {

        //商品订单信息更新大订单信息
        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderIds.get(0));
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(litemallOrderGoods.getOrderId());
        litemallOrder.setOrderStatus(OrderUtil.STATUS_RETURN_SELF);
        litemallOrderMapper.updateByPrimaryKeySelective(litemallOrder);
        System.out.println(litemallOrder.getId());

        AgedmallLeaseGoodsReturnRecord agedmallLeaseGoodsReturnRecord = backendOrderMapper.pickUpLeaseReturnRecord(litemallOrder.getId(), id);
        if (null != agedmallLeaseGoodsReturnRecord) {
            if (null != agedmallLeaseGoodsReturnRecord.getUpdoorType()) {
                agedmallLeaseGoodsReturnRecord.setUpdoorType(ship);
                //配送人员
                if (!"".equals(deliveryManId)) {
                    agedmallLeaseGoodsReturnRecord.setUpdoorManId(Integer.parseInt(deliveryManId));
                }
                agedmallLeaseGoodsReturnRecord.setExpressName(expressCompany);
                agedmallLeaseGoodsReturnRecord.setExpressCode(expressCode);
                //维护人员
                if (!"".equals(maintainManId)) {
                    agedmallLeaseGoodsReturnRecord.setMaintainManId(Integer.parseInt(maintainManId));
                }
                agedmallLeaseGoodsReturnRecordMapper.updateByPrimaryKeySelective(agedmallLeaseGoodsReturnRecord);
            }
        } else {
            // 添加归还表
            AgedmallLeaseGoodsReturnRecord agedmallLeaseGoodsReturnRecordInsert = new AgedmallLeaseGoodsReturnRecord();
            agedmallLeaseGoodsReturnRecordInsert.setBigOrderId(litemallOrder.getId() + "");
            //agedmallLeaseGoodsReturnRecord.setSubOrderIds(StringUtils.join(id, ","));
            agedmallLeaseGoodsReturnRecordInsert.setSubOrderIds(id.toString());
            agedmallLeaseGoodsReturnRecordInsert.setGetGoodsStyle(ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP);
            agedmallLeaseGoodsReturnRecordInsert.setUpdoorType(ship);
            agedmallLeaseGoodsReturnRecordInsert.setUpdoorPrice(BigDecimal.ZERO);
            if (!"".equals(deliveryManId) && !"all".equals(deliveryManId) && !"sort".equals(deliveryManId)) {
                agedmallLeaseGoodsReturnRecordInsert.setUpdoorManId(Integer.parseInt(deliveryManId));
            }
            agedmallLeaseGoodsReturnRecordInsert.setExpressName(expressCompany);
            agedmallLeaseGoodsReturnRecordInsert.setExpressCode(expressCode);
            agedmallLeaseGoodsReturnRecordInsert.setAddTime(LocalDateTime.now());
            agedmallLeaseGoodsReturnRecordInsert.setUpdateTime(LocalDateTime.now());
            agedmallLeaseGoodsReturnRecordMapper.insertSelective(agedmallLeaseGoodsReturnRecordInsert);
        }
        //获取子订单信息
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(id);
        //归还 门店配送 或者 三方物流
        if (DeliveryTypeEnum.STORE.getCode().equals(ship)) {
            packageLogistics(maintainManId, deliveryManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "归还", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        } else {
            packageLogistics("", maintainManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        }
        LitemallOrderGoodsExample litemallOrderGoodsExampl = new LitemallOrderGoodsExample();
        litemallOrderGoodsExampl.or().andChildOrderIdEqualTo(id.longValue());
        List<LitemallOrderGoods> orderGoodsLists = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExampl);

        //更新商品的状态信息
        for (int i = 0; i < orderIds.size(); i++) {
            LitemallOrderGoods litemallOrderGoodsUpdate = new LitemallOrderGoods();
            litemallOrderGoodsUpdate.setId(orderIds.get(i));
            litemallOrderGoodsUpdate.setUpdateTime(LocalDateTime.now());
            //待商家收货
            //litemallOrderGoodsUpdate.setOrderGoodsStat(OrderUtil.STATUS_RETURN_SELF.intValue());
            litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoodsUpdate);
        }
        //更新子订单的状态信息
        if (orderGoodsLists.size() == orderIds.size()) {
            litemallOrderItem.setOrderStatus(OrderUtil.STATUS_RETURN_SELF);
            litemallOrderItem.setId(id);
            litemallOrderItem.setUpdateTime(LocalDateTime.now());
            litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
        }
        return ResponseUtil.ok();
    }

    /**
     * * 待商户收货-取货 订单商品状态变更（若客户付款金额足够，商品状态变更为已完成，若客户金额不足，商品状态变更为待客户结算）
     * * 租赁商品归还表-> 添加归还状态-> 结算大订单-> 更新包裹的信息 添加维护人员信息
     *
     * @param id
     * @param orderIds
     * @param deliveryManId
     * @param maintainManId
     * @param ship
     * @param expressCompany
     * @param expressCode
     * @return
     */
    public Object notTakingByBusinessTake(Integer id, List<Integer> orderIds, String deliveryManId, String maintainManId, Integer ship, String expressCompany, String expressCode) {
        // 结算大订单
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(id);
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(litemallOrderItem.getParentId());
        //计算金额   若客户付款金额足够，商品状态变更为已完成，若客户金额不足，商品状态变更为待客户结算  OrderUtil
        leaseOrderService.orderSettlement(litemallOrder.getOrderSn(), litemallOrderItem.getChildOrderCode());
        //获取全部包裹信息
        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        agedmallLgBaseInfoExample.or().andOrderCodeEqualTo(litemallOrder.getOrderSn());
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);

        //获取子订单下所有的商品信息
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(id.longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);

        AgedmallLeaseGoodsReturnRecord agedmallLeaseGoodsReturnRecord = agedmallLeaseGoodsReturnRecordMapper.selectByPrimaryKey(litemallOrderGoodsList.get(0).getId());
        agedmallLeaseGoodsReturnRecord.setReceiveTime(LocalDateTime.now());
        agedmallLeaseGoodsReturnRecord.setEndTime(LocalDateTime.now());
        //租赁商品归还表
        agedmallLeaseGoodsReturnRecordMapper.updateByPrimaryKeySelective(agedmallLeaseGoodsReturnRecord);
        // 添加归还状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_RETURN, agedmallLeaseGoodsReturnRecord.getId(), ProcessStateConstant.RETURN_STATE_SIGN);

        //归还 门店配送 或者 三方物流
        if (DeliveryTypeEnum.STORE.getCode().equals(ship)) {
            packageLogistics(maintainManId, deliveryManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "归还", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        } else {
            packageLogistics("", maintainManId, ship, id, orderIds, LgBaseInfoStatConstant.RETURNING, LgBaseInfoLgType.GIVEBACK.getCode(), expressCompany, expressCode, "", "维护", LogisticsMissionTypeEnum.RETURN.getCode(), LogisticsMissionTypeEnum.MAINTAIN.getCode(), "");
        }

        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(litemallOrderGoodsList.get(0).getId());
        litemallOrderGoods.setId(litemallOrderGoodsList.get(0).getId());
        litemallOrderGoods.setUpdateTime(LocalDateTime.now());
        //601 交易完成
        litemallOrderGoods.setOrderGoodsStat(OrderUtil.STATUS_RETURN_SUCCESS.intValue());
        litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
        if (litemallOrderGoodsList.size() == 1) {
            //变更商品订单状态
            litemallOrderItem.setId(id);
            //订单商品表状态变成 交易完成
            litemallOrderItem.setOrderStatus(OrderUtil.STATUS_RETURN_SUCCESS);
            litemallOrderItem.setUpdateTime(LocalDateTime.now());
            litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
        }
        return ResponseUtil.ok();
    }

    /**
     * @param id 取消包裹重新打包  判断能否取消包裹   更新原包裹的状态 更新订单的状态
     * @return
     */
    public Object cancelPack(Integer id) {
        //获取包裹信息
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(id.longValue());
        if (null == agedmallLgBaseInfo) {
            return ResponseUtil.ok();
        }
        /**
         * 配送中
         *   public static final Integer BUY_SENDING=14;
         *已配送
         *   public static final Integer BUY_SEND_COMPLETE=15;
         */
        if ((LgBaseInfoStatConstant.BUY_SENDING.equals(agedmallLgBaseInfo.getLgStat())) && (LgBaseInfoStatConstant.BUY_SEND_COMPLETE.equals(agedmallLgBaseInfo.getLgStat()))) {
            throw new BizException("已配送，不能取消包裹");
        }
        agedmallLogisticsPackageInfoMapper.logicalDeleteByPrimaryKey(id);
        //修改包裹信息  包裹取消
        agedmallLgBaseInfo.setId(id.longValue());
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.CANCEL.getCode());
        agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());

        //将取消打包的包裹里面的商品的 package_id 更新为空
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());
        List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
        for (LogisticsGoodsData logisticsGoodsData : goodsDataList) {
            LitemallOrderGoods litemallOrderGoods = new LitemallOrderGoods();
            litemallOrderGoods.setId(logisticsGoodsData.getOrderGoodsId());
            litemallOrderGoods.setUpdateTime(LocalDateTime.now());
            litemallOrderGoods.setPackageId(null);
            litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
        }
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //AgedmallLgBaseInfo lgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(id.longValue());

        //lgBaseInfo.getLgContent()
        //修改对应的mission表的信息
        AgedmallLgMissionExample agedmallLgMissionExample = new AgedmallLgMissionExample();
        agedmallLgMissionExample.or().andBaseInfoIdEqualTo(id);
        List<AgedmallLgMission> agedmallLgMissions = agedmallLgMissionMapper.selectByExample(agedmallLgMissionExample);
        //List<Integer> agedMissionIds = new ArrayList<>();
        for (AgedmallLgMission agedmallLgMission : agedmallLgMissions) {
            //修改misison表的状态
            agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.CANCEL.getCode());
            agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
        }
        return ResponseUtil.ok();
    }

    public Object orderSetting(OrderSettingVo orderSettingVo) {
        AgedmallOrderSetting agedmallOrderSetting;
        AgedmallOrderSettingExample orderSettingExample = new AgedmallOrderSettingExample();
        orderSettingExample.or();
        List<AgedmallOrderSetting> settingList = agedmallOrderSettingMapper.selectByExample(orderSettingExample);
        if (settingList != null && settingList.size() > 0) {
            agedmallOrderSetting = settingList.get(0);
        } else {
            agedmallOrderSetting = new AgedmallOrderSetting();
            agedmallOrderSetting.setAddTime(LocalDateTime.now());
            agedmallOrderSetting.setBusId(orderSettingVo.getShopId().longValue());
        }
        agedmallOrderSetting.setStockReduceType(orderSettingVo.getStockDeduct());
        agedmallOrderSetting.setStockPreemption(orderSettingVo.getStockPreemption());
        agedmallOrderSetting.setCancleOrder(orderSettingVo.getCancleOrder());
        agedmallOrderSetting.setConfirmTake(orderSettingVo.getConfirmTake());
        agedmallOrderSetting.setBackComfirmTake(orderSettingVo.getBackComfirmTake());
        agedmallOrderSetting.setReturnEquipment(orderSettingVo.getReturnEquipment());
        agedmallOrderSetting.setAfterSaleRefund(orderSettingVo.getAfterSaleRefund());
        if (settingList != null && settingList.size() > 0) {
            agedmallOrderSettingMapper.updateByPrimaryKey(agedmallOrderSetting);
        } else {
            agedmallOrderSettingMapper.insertSelective(agedmallOrderSetting);
        }
        return ResponseUtil.ok();
    }

    public Object getOrderSetting(Integer shopId) {
        AgedmallOrderSettingExample orderSettingExample = new AgedmallOrderSettingExample();
        orderSettingExample.or().andBusIdEqualTo(shopId.longValue());
        AgedmallOrderSetting settingList = agedmallOrderSettingMapper.selectOneByExample(orderSettingExample);
        return ResponseUtil.ok(settingList);
    }

    /**
     * @param orderid 子订单id
     * @return
     */
    public Object usingBuyOutLoad(Integer orderid) {
        List<OrderDetailSubOrderListGoodsVo> goodsList = backendOrderMapper.getOrderDetailSubOrderListGoodsVosNoSelf(orderid);
        BuyOutLoadVo buyOutLoadVo = new BuyOutLoadVo();
        goodsList.stream().forEach(q -> {
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
        });
        buyOutLoadVo.setGoodsList(goodsList);
        return ResponseUtil.ok(buyOutLoadVo);
    }

    public Object returnCompleteEvent(Integer suOrderId) {
        //计算价格
        //leaseOrderService.orderSettlement(baseInfo.getOrderCode(), orderGoods.getChildOrderCode());
        List<OrderDetailSubOrderListGoodsVo> goodsList = backendOrderMapper.getOrderDetailSubOrderListGoodsVosNoSelf(suOrderId);

        goodsList.stream().forEach(q -> {
            q.setOrderState(OrderUtil.backendShowType(q.getOrderState().shortValue()));
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(q.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            q.setGoodsSpec(spec.replaceFirst(",", ""));
        });
        ReturnCompleteVo returnCompleteVo = new ReturnCompleteVo();
        returnCompleteVo.setGoodsList(goodsList);
        return ResponseUtil.ok(returnCompleteVo);
    }

    public Object getSubOrderAndGoodsInformation(int orderItemId) {
        SubOrderAndGoodsInformationOrderListVo subOrderAndGoodsInformationOrderListVo = new SubOrderAndGoodsInformationOrderListVo();
        List<GoodsInformation> goodsInfoList = subOrderAndCommodityRelatedOperationsMapper.getGoodsInfo(orderItemId);
        goodsInfoList.stream().forEach(goodsInformation -> {
            List<LitemallGoodsProductSpecification> specifications = JSON.parseArray(goodsInformation.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            BigDecimal buyNumber = new BigDecimal(goodsInformation.getNumber());
            goodsInformation.setTotalPrice(goodsInformation.getPrice().multiply(buyNumber));
            String spec = "";
            if (CollectionUtils.isNotEmpty(specifications)) {
                for (LitemallGoodsProductSpecification specification : specifications) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            goodsInformation.setGoodsSpec(spec.replaceFirst(",", ""));
        });
        if (goodsInfoList.size() > 0) {
            subOrderAndGoodsInformationOrderListVo.setSufreightprice(goodsInfoList.get(0).getSufreightprice());
            subOrderAndGoodsInformationOrderListVo.setType(goodsInfoList.get(0).getType());
            subOrderAndGoodsInformationOrderListVo.setOrderId(goodsInfoList.get(0).getOrderId());
            subOrderAndGoodsInformationOrderListVo.setRemark(goodsInfoList.get(0).getRemark());
            subOrderAndGoodsInformationOrderListVo.setStoreName(goodsInfoList.get(0).getStoreName());
            subOrderAndGoodsInformationOrderListVo.setChildOrderCode(goodsInfoList.get(0).getChildOrderCode());
            List<GoodsInformation> goodsInformationList = new ArrayList<>(3);
            for (int i = 0; i < goodsInfoList.size(); i++) {
                GoodsInformation goodsInformation = new GoodsInformation();
                goodsInformation.setTotalPrice(goodsInfoList.get(i).getTotalPrice());
                goodsInformation.setGoodsSpec(goodsInfoList.get(i).getGoodsSpec());
                goodsInformation.setFreightPrice(goodsInfoList.get(i).getFreightPrice());
                goodsInformation.setGoodsName(goodsInfoList.get(i).getGoodsName());
                goodsInformation.setNumber(goodsInfoList.get(i).getNumber());
                goodsInformation.setGoodsPic(goodsInfoList.get(i).getGoodsPic());
                goodsInformation.setGoodsName(goodsInfoList.get(i).getGoodsName());
                goodsInformation.setGoodsSn(goodsInfoList.get(i).getGoodsSn());
                goodsInformation.setStoreGoodsId(goodsInfoList.get(i).getStoreGoodsId());
                goodsInformation.setPrice(goodsInfoList.get(i).getPrice());
                goodsInformation.setStoreName(goodsInfoList.get(i).getStoreName());
                goodsInformationList.add(goodsInformation);
            }
            subOrderAndGoodsInformationOrderListVo.setGoodsInformation(goodsInformationList);
        }
        return ResponseUtil.ok(subOrderAndGoodsInformationOrderListVo);
    }


    public Object updatePriceAndFreight(OrderPriceAndFreight orderPriceAndFreight) {
        LitemallOrderItem litemallOrderItem = new LitemallOrderItem();
        //根据子订单id 查出旧的运费
        LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderPriceAndFreight.getSubOrderId());
        //根据子订单id查询出该订单下的商品
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo((long) orderPriceAndFreight.getSubOrderId());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
        //子订单下的商品的数量
        int size = litemallOrderGoodsList.size();
        //子订单下的商品的数量
        BigDecimal sizeCount = new BigDecimal(size);
        //旧的运费
        BigDecimal agoFreightPrice = orderItem.getFreightPrice();
        //修改后的运费
        BigDecimal newFreight = new BigDecimal(orderPriceAndFreight.getNewFreight());
        String subtractNewFreight = agoFreightPrice.subtract(newFreight).toString();
        BigDecimal changedShipping;
        //格式化的运费
        BigDecimal formatFreight;
        //判断运费是涨价还是降价
        //运费降价   0.01 Integer.parseInt(subtractNewFreight)
        if (Double.parseDouble(subtractNewFreight) >= 0) {
            changedShipping = newFreight.divide(sizeCount);
            formatFreight = changedShipping.setScale(2, BigDecimal.ROUND_HALF_UP);
            for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsList) {
                //更新单个商品的运费
                litemallOrderGoods.setFreightPrice(formatFreight);
                litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
            }
        } else {
            changedShipping = newFreight.abs().divide(sizeCount);
            formatFreight = changedShipping.setScale(2, BigDecimal.ROUND_HALF_UP);
            //更新单个商品的运费
            for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsList) {
                litemallOrderGoods.setFreightPrice(formatFreight);
                litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
            }
        }

        //更新商品的售价
        List<GoodsList> orderPriceAndFreightGoodsList = orderPriceAndFreight.getGoodsList();
        List<LitemallOrderGoods> litemallOrderGoodsFilter = new ArrayList<>();
        BigDecimal suTotalPrice = BigDecimal.ZERO;
        for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsList) {
            if(orderPriceAndFreightGoodsList == null) {
                continue;
            }
            for (GoodsList goodsList : orderPriceAndFreightGoodsList) {
                //goodsExample.or().andChildOrderIdEqualTo((long)orderPriceAndFreight.getSubOrderId()).andIdEqualTo(goodsList.getGoodsId());
                if (litemallOrderGoods.getGoodsId() == goodsList.getGoodsId()) {
                    Short number = litemallOrderGoods.getNumber();
                    BigDecimal Price = new BigDecimal(goodsList.getPrice());
                    BigDecimal Bnumber = new BigDecimal(number);
                    //保留两位小数
                    BigDecimal countPrice = Price.multiply(Bnumber);
                    suTotalPrice = suTotalPrice.add(countPrice.setScale(2, BigDecimal.ROUND_HALF_UP));

                    litemallOrderGoods.setPrice(new BigDecimal(goodsList.getPrice()));
                    litemallOrderGoodsFilter.add(litemallOrderGoods);
                }
            }
        }
        //更新子订单的运费及总价
        litemallOrderItem.setFreightPrice(newFreight);
        litemallOrderItem.setGoodsPrice(suTotalPrice);
        litemallOrderItem.setOrderPrice(suTotalPrice);
        //litemallOrderItem.setActualPrice(suTotalPrice);
        litemallOrderItem.setId(orderPriceAndFreight.getSubOrderId());
        litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
        //更新商品的价格
        for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsFilter) {
            litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
        }
        //通过parentid获取所有子订单
        LitemallOrderItem item = litemallOrderItemMapper.selectByPrimaryKey(orderPriceAndFreight.getSubOrderId());
        LitemallOrderItemExample litemallOrderItemExample = new LitemallOrderItemExample();
        litemallOrderItemExample.or().andParentIdEqualTo(item.getParentId());
        List<LitemallOrderItem> litemallOrderItems = litemallOrderItemMapper.selectByExample(litemallOrderItemExample);
        //计算子订单的总运费及总价格
        BigDecimal freightPrice = BigDecimal.ZERO;
        BigDecimal totalFreightPrice = BigDecimal.ZERO;
        BigDecimal onePrice = BigDecimal.ZERO;
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (LitemallOrderItem litemallOrderItemUpdate : litemallOrderItems) {
            onePrice=litemallOrderItemUpdate.getGoodsPrice();
            freightPrice = litemallOrderItemUpdate.getFreightPrice();
            totalFreightPrice=totalFreightPrice.add(freightPrice);
            totalPrice=totalPrice.add(onePrice);
        }
        LitemallOrder litemallOrder = new LitemallOrder();
        litemallOrder.setId(item.getParentId());
        litemallOrder.setFreightPrice(totalFreightPrice);
        litemallOrder.setGoodsPrice(totalPrice);
        litemallOrder.setOrderPrice(totalPrice);
        //litemallOrder.setActualPrice(totalPrice);
        litemallOrderMapper.updateByPrimaryKeySelective(litemallOrder);
        return ResponseUtil.ok();
    }


    /**
     * 订单待结算 修改价格
     *
     * @param settledUpdatePriceVo
     * @return
     */
    public Object toBeSettledUpdatePrice(SettledUpdatePriceVo settledUpdatePriceVo) {
        LitemallOrderItem litemallOrderItem = new LitemallOrderItem();
        //根据子订单id 查出旧的运费
        LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(settledUpdatePriceVo.getSubOrderId());
        //根据子订单id查询出该订单下的商品
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo((long) settledUpdatePriceVo.getSubOrderId());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);

        litemallOrderItem.setId(settledUpdatePriceVo.getSubOrderId());
        litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);

        //更新商品的售价
        List<GoodsList> orderPriceAndFreightGoodsList = settledUpdatePriceVo.getGoodsList();
        List<LitemallOrderGoods> litemallOrderGoodsFilter = new ArrayList<>();
        //过滤掉不用更新价格的商品
        BigDecimal suBigDecimal = new BigDecimal(0);
        for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsList) {
            for (GoodsList goodsList : orderPriceAndFreightGoodsList) {
                //goodsExample.or().andChildOrderIdEqualTo((long)orderPriceAndFreight.getSubOrderId()).andIdEqualTo(goodsList.getGoodsId());
                if (litemallOrderGoods.getGoodsId() == goodsList.getGoodsId()) {
                    Short number = litemallOrderGoods.getNumber();
                    BigDecimal Price = new BigDecimal(goodsList.getPrice());
                    BigDecimal Bnumber = new BigDecimal(number);
                    //保留两位小数
                    BigDecimal countPrice = Price.setScale(2, BigDecimal.ROUND_HALF_UP).multiply(Bnumber);
                    suBigDecimal = suBigDecimal.add(countPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                    litemallOrderGoods.setPrice(new BigDecimal(goodsList.getPrice()));
                    litemallOrderGoodsFilter.add(litemallOrderGoods);
                }
            }
        }
        //更新子订单的运费及总价
        litemallOrderItem.setGoodsPrice(suBigDecimal);
        litemallOrderItem.setId(settledUpdatePriceVo.getSubOrderId());
        litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
        //更新商品的价格
        for (LitemallOrderGoods litemallOrderGoods : litemallOrderGoodsFilter) {
            litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
        }

        LitemallOrderItem litemallOrderItem1 = new LitemallOrderItem();
        litemallOrderItem1.setId(settledUpdatePriceVo.getSubOrderId());
        //通过parentid获取所有子订单
        LitemallOrderItem item = litemallOrderItemMapper.selectByPrimaryKey(litemallOrderItem1.getId());
        LitemallOrderItemExample litemallOrderItemExample = new LitemallOrderItemExample();
        litemallOrderItemExample.or().andParentIdEqualTo(item.getParentId());
        List<LitemallOrderItem> litemallOrderItems = litemallOrderItemMapper.selectByExample(litemallOrderItemExample);
        //计算子订单的总价格
        BigDecimal onePrice = new BigDecimal(0);
        BigDecimal totalPrice = new BigDecimal(0);
        for (LitemallOrderItem litemallOrderItem2 : litemallOrderItems) {
            onePrice = litemallOrderItem2.getGoodsPrice();
            totalPrice.add(onePrice);
        }
        LitemallOrder litemallOrder = new LitemallOrder();
        litemallOrder.setId(item.getParentId());
        litemallOrder.setGoodsPrice(totalPrice);
        litemallOrderMapper.updateByPrimaryKeySelective(litemallOrder);
        return ResponseUtil.ok();
    }


    public Object packUserId(Integer orderId, String packUserId) {
        //获取子订单信息
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
        //获取子订单每件商品情况
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(orderId.longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
        //获取大订单信息
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        litemallOrderExample.or().andIdEqualTo(litemallOrderItem.getParentId());

        //获取商品的id
        List<Integer> orderGoodsIdList = new ArrayList<>();
        litemallOrderGoodsList.forEach(orderGoodss -> orderGoodsIdList.add(orderGoodss.getId()));
        //packageLogistics(String deliveryUserId, String packUserId, Integer deliveryType, Integer suOrderId, List<Integer> orderGoodsIdsList, Integer packageLogisticsType, Integer LgType, String expressId, String shipSn, String deliveryUserBusiNode, String packUserBusiNode)
        packageLogistics(packUserId, "", DeliveryTypeEnum.SELFMENTION.getCode(), orderId, orderGoodsIdList, LgBaseInfoStatConstant.PICK_UP_ALLOTING, LgBaseInfoLgType.SELFPICKUP.getCode(), "", "", "配货", "", LogisticsMissionTypeEnum.ALLOT.getCode(), null, "");

        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsList.get(0);

        litemallOrderItem.setExtractShop(litemallOrderGoods.getStoreId());
        //自提时间
        litemallOrderItem.setExtractTime(LocalDateTime.now());
        //更新时间
        litemallOrderItem.setUpdateTime(LocalDateTime.now());
        //订单状态待用户自提
        litemallOrderItem.setOrderStatus((short) 302);
        litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
        return ResponseUtil.ok();
    }

    /**
     * 用户 自提 已取货
     *
     * @param orderId 子订单id
     * @param pickId  包裹id
     * @return
     */
    public Object take(Integer orderId, Integer pickId) {
        //获取子订单信息
        LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderId);
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(orderItem.getParentId());
        //获取商品 订单商品表信息
        LitemallOrderGoodsExample litemallOrderGoodsExample = new LitemallOrderGoodsExample();
        litemallOrderGoodsExample.or().andChildOrderIdEqualTo(orderId.longValue());
        List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(litemallOrderGoodsExample);
        LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsList.get(0);
        //判断包裹是否配货完成
        //boolean finishSubOrderLogistics = isFinishSubOrderLogistics(orderItem.getOrderCode(), Integer.parseInt(orderItem.getChildOrderCode()));
        //自提码
        //litemallOrderItem.setExtractCode();
        orderItem.setExtractShop(litemallOrderGoods.getStoreId());
        //自提时间
        orderItem.setExtractTime(LocalDateTime.now());
        //更新时间
        orderItem.setUpdateTime(LocalDateTime.now());
        //订单状态待用户自提 售卖商品 用户确认收货，订单结束； (short) 401
        orderItem.setOrderStatus(OrderUtil.STATUS_CONFIRM);
        litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);
        if (null != litemallOrder) {
            litemallOrder.setFinishTime(LocalDateTime.now());
            //litemallOrder.setExtractCode();
            litemallOrder.setExtractShop(litemallOrderGoods.getStoreId());
            litemallOrder.setFinishTime(LocalDateTime.now());
            litemallOrderMapper.updateByPrimaryKeySelective(litemallOrder);
        }

        //更新包裹的信息
        //获取包裹信息
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(pickId.longValue());
        if (null == agedmallLgBaseInfo) {
            return ResponseUtil.ok();
        }


        //agedmallLogisticsPackageInfoMapper.logicalDeleteByPrimaryKey(pickId);
        //修改包裹信息  包裹结束
        agedmallLgBaseInfo.setLgStat(LgBaseInfoStatConstant.PICK_UP_COMPLETE);
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //修改对应的mission表的信息
        AgedmallLgMissionExample agedmallLgMissionExample = new AgedmallLgMissionExample();
        agedmallLgMissionExample.or().andBaseInfoIdEqualTo(pickId);
        List<AgedmallLgMission> agedmallLgMissionList = agedmallLgMissionMapper.selectByExample(agedmallLgMissionExample);
        if (agedmallLgMissionList.size() > 0) {
            for (AgedmallLgMission agedmallLgMission : agedmallLgMissionList) {
                //修改misison表的状态
                agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
                agedmallLgMission.setUpdateTime(LocalDateTime.now());
                agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
            }

            AgedmallLgBusiRecordExample agedmallLgBusiRecordExample = new AgedmallLgBusiRecordExample();

            agedmallLgBusiRecordExample.or().andMissionIdEqualTo(agedmallLgMissionList.get(0).getId().longValue()).andBusiStatEqualTo(SelfNodeEnum.DISTRIBUTIONCOMPLETED.getCode());

            AgedmallLgBusiRecord lgBusiRecord = agedmallLgBusiRecordMapper.selectOneByExample(agedmallLgBusiRecordExample);
            //自提配货完成
            if (null != lgBusiRecord) {
                //添加物流流水表
                AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
                agedmallLgBusiRecord.setLgType(LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode());
                agedmallLgBusiRecord.setBusiStat(SelfNodeEnum.SELFCOMPLETED.getCode());
                //agedmallLgBusiRecord.setUpdateTime(LocalDateTime.now());
                agedmallLgBusiRecord.setCreatedTime(LocalDateTime.now());
                agedmallLgBusiRecord.setCreatedBy("auto");
                agedmallLgBusiRecord.setMissionId(agedmallLgMissionList.get(0).getId().longValue());
                agedmallLgBusiRecord.setBusiTime(LocalDateTime.now());
                agedmallLgBusiRecord.setReceiveOrderId(null);
                agedmallLgBusiRecordMapper.insertSelective(agedmallLgBusiRecord);
            }
        }
        return ResponseUtil.ok();
    }

    /**
     * 判断物流是否完成
     * Integer agedmallLgBaseInfosLgStat
     *
     * @return
     */
    public boolean isFinishSubOrderLogistics(String bigOrderSn, Integer subOrderId) {
        AgedmallLgBaseInfoExample baseInfoExample = new AgedmallLgBaseInfoExample();
        baseInfoExample.or().andOrderCodeEqualTo(bigOrderSn);
        List<AgedmallLgBaseInfo> agedmallLgBaseInfos = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(baseInfoExample);
        for (int i = 0; i < agedmallLgBaseInfos.size(); i++) {
            List<Integer> orderGoodsIds = logisticBusiBaseServiceImpl.getorderGoodsIds(agedmallLgBaseInfos.get(i).getLgContent());
            logger.debug("确认订单获取的订单商品id {},{},{}", JSONObject.toJSONString(orderGoodsIds), bigOrderSn, subOrderId);
            LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsIds.get(0));
            logger.debug("确认订单获取的订单商品 {},{},{},{}", orderGoods.getChildOrderId(), agedmallLgBaseInfos.get(i).getLgIsOver()
                    , bigOrderSn, subOrderId);
            if (orderGoods.getChildOrderId().intValue() == subOrderId && agedmallLgBaseInfos.get(i).getLgIsOver().equals(LgBaseInfoIsOverEnum.END.getCode())) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param deliveryUserId/maintainId             配送员/维护员id
     * @param packUserId                            配货员id
     * @param deliveryType                          物流方式
     * @param suOrderId                             子订单id
     * @param orderGoodsIdsList                     订单商品id
     * @param packageLogisticsType                  当前物流状态
     * @param LgType                                物流类型
     * @param expressId                             快递公司的id
     * @param shipSn                                物流的id
     * @param deliveryUserBusiNode                  物流的节点  deliveryUserId不为空 deliveryUserBusiNode也不为空
     * @param packUserBusiNode                      物流的节点    packUserId不为空  packUserBusiNode也不为空
     * @param lgMissionType                         任务类型
     * @param agedmallLgMissionManRecordMissionType 物流 -手动分配配货配送人员记录表 类型
     * @param maintainId                            换货时才会传入 维护人员   maintainId
     * @return
     */
    public BaseInfoIdAndOrderSn packageLogistics(String deliveryUserId, String packUserId, Integer deliveryType, Integer suOrderId, List<Integer> orderGoodsIdsList, Integer packageLogisticsType, Integer LgType, String expressId, String shipSn, String deliveryUserBusiNode, String packUserBusiNode, Integer lgMissionType, Integer agedmallLgMissionManRecordMissionType, String maintainId) {
        List<LitemallOrderGoods> litemallGoodsList = new ArrayList<>();
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(suOrderId);
        LitemallOrder bigOrder = litemallOrderMapper.selectByPrimaryKey(litemallOrderItem.getParentId());
        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        agedmallLgBaseInfoExample.or().andOrderCodeEqualTo(bigOrder.getOrderSn());
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
        BaseInfoIdAndOrderSn baseInfoIdAndOrderSn = new BaseInfoIdAndOrderSn();

        if (orderGoodsIdsList.size() > 0) {
            for (Integer orderGoodsId : orderGoodsIdsList) {
                LitemallOrderGoods litemallOrderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
                litemallGoodsList.add(litemallOrderGoods);
            }
        }

        Integer baseInfoId = 0;
        AgedmallLgBaseInfo lgBaseInfo = new AgedmallLgBaseInfo();
        if (agedmallLgBaseInfoList.size() > 0) {
            for (int i = 0; i < agedmallLgBaseInfoList.size(); i++) {
                AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoList.get(i);
                Long agedmallLgBaseInfoId = agedmallLgBaseInfo.getId();
                LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfoList.get(i).getLgContent());
                List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
                for (int j = 0; j < goodsDataList.size(); j++) {
                    LogisticsGoodsData logisticsGoodsData = goodsDataList.get(j);
                    for (int k = 0; k < litemallGoodsList.size(); k++) {
                        LitemallOrderGoods litemallOrderGoods = litemallGoodsList.get(k);
                        if (logisticsGoodsData.getOrderGoodsId().equals(litemallOrderGoods.getId())) {
                            baseInfoId = agedmallLgBaseInfoId.intValue();
                        }
                    }
                }
            }
            lgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue());
        }


        LgData lgData = new LgData();
        LgDataUser lgDataUser = new LgDataUser();
        LgDateThird lgDateThird = new LgDateThird();
        List<LgData> lgDataList = new ArrayList<>();
        //配货员配货类型
        if (!"".equals(packUserId)) {
            if ("sort".equals(packUserId)) {
                lgData.setReceiveOrderMode("sort");
            } else if ("all".equals(packUserId)) {
                lgData.setReceiveOrderMode("all");
            } else {
                //指定配货人员
                lgData.setReceiveOrderMode("assign");
                AgedmallDeliveryManInfo agedmallDeliveryManInfos = agedmallDeliveryManInfoMapper.selectByPrimaryKey(Integer.parseInt(packUserId));
                //AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(Integer.parseInt(deliveryUserId));
                if (null != agedmallDeliveryManInfos) {
                    lgDataUser.setUid(agedmallDeliveryManInfos.getId());
                    lgDataUser.setUserName(agedmallDeliveryManInfos.getUsername());
                    lgDataUser.setPhone(agedmallDeliveryManInfos.getPhone());
                }
                lgData.setLgDataUser(lgDataUser);
            }
        }
        //选择第三方物流时才会有名称和的单号
        if (deliveryType.equals(DeliveryTypeEnum.LOGISTICS.getCode())) {
            AgedmallExpress agedmallExpress = new AgedmallExpress();
            if (!"".equals(expressId)) {
                agedmallExpress = agedmallExpressMapper.selectByPrimaryKey(Long.valueOf(expressId).longValue());
            }

            //快递公司名称
            lgDateThird.setCompany(agedmallExpress.getName());
            //物流单号
            lgDateThird.setLgOrderCode(shipSn);
            lgData.setLgDateThird(lgDateThird);
            //物流节点
            lgData.setBusiNode(deliveryUserBusiNode);
            lgData.setLgMode("third");
            lgDataList.add(lgData);
        } else {
            if (!"".equals(deliveryUserBusiNode)) {
                lgData.setLgMode("store");
                //物流节点
                lgData.setBusiNode(deliveryUserBusiNode);
                lgDataList.add(lgData);
            }
            //门店配送  第三方物流和自提不走
            if (!"".equals(packUserBusiNode)) {
                LgData lgDataDeliver = new LgData();
                LgDataUser lgDataUserDeliver = new LgDataUser();
                LgDateThird lgDateThirdDeliver = new LgDateThird();
                //配送员抢单类型
                if ("sort".equals(deliveryUserId)) {
                    lgDataDeliver.setReceiveOrderMode("sort");
                } else if ("all".equals(deliveryUserId)) {
                    lgDataDeliver.setReceiveOrderMode("all");
                } else {
                    //指定人员
                    lgDataDeliver.setReceiveOrderMode("assign");
                    //AgedmallDeliveryManInfoExample agedmallDeliveryManInfoExample = new AgedmallDeliveryManInfoExample();
                    //agedmallDeliveryManInfoExample.or().andUserIdEqualTo(Long.parseLong(deliveryUserId));
                    AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(Integer.parseInt(deliveryUserId));
                    if (null != agedmallDeliveryManInfo) {
                        lgDataUserDeliver.setUid(agedmallDeliveryManInfo.getId());
                        lgDataUserDeliver.setUserName(agedmallDeliveryManInfo.getUsername());
                        lgDataUserDeliver.setPhone(agedmallDeliveryManInfo.getPhone());
                    }
                    lgDataDeliver.setLgDataUser(lgDataUser);
                }
                lgDateThirdDeliver.setCompany("");
                lgDateThirdDeliver.setLgOrderCode("");
                lgDataDeliver.setLgDateThird(lgDateThird);
                lgDataDeliver.setLgMode("store");
                //业务节点
                lgDataDeliver.setBusiNode(packUserBusiNode);
                lgDataList.add(lgDataDeliver);
            }
        }

        if (null != lgBaseInfo && LgBaseInfoIsOverEnum.START.getCode().equals(lgBaseInfo.getLgIsOver())) {
            JSONArray jsonArray = (JSONArray) JSONArray.toJSON(lgDataList);
            String lgDateJSONString = jsonArray.toJSONString();

            // 添加物流节点
            AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
            agedmallLgBaseInfo.setId(lgBaseInfo.getId());
            agedmallLgBaseInfo.setOrderCode(bigOrder.getOrderSn());
            //具体的节点
            agedmallLgBaseInfo.setLgType(LgType);
            agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIdsList, null));
            agedmallLgBaseInfo.setUserName(bigOrder.getConsignee());
            agedmallLgBaseInfo.setPhone(bigOrder.getMobile());
            agedmallLgBaseInfo.setAddresss(bigOrder.getAddress());
            agedmallLgBaseInfo.setWarehouseType(litemallGoodsList.get(0).getStockType() == 3 ? 1 : 0);
            //LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfoList.get(i).getLgContent());
            agedmallLgBaseInfo.setLgUserConf(lgDateJSONString);
            //物流模式：1 门店，2第三方物流
            agedmallLgBaseInfo.setLgMode(deliveryType.byteValue());
            Integer noticeType = 0;
            //                           0-门店 1-链条锁 2-衣柜锁 3-云仓
            if (litemallGoodsList.get(0).getStockType() == 3) {
                AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(litemallGoodsList.get(0).getStoreId());
                agedmallLgBaseInfo.setWarehouseAddress(cloudHouse.getAddressDetail());
                agedmallLgBaseInfo.setStoreId(cloudHouse.getId());
                noticeType = 2;
            } else {
                AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(litemallGoodsList.get(0).getStoreId().longValue());
                agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
                agedmallLgBaseInfo.setStoreId(store.getId().intValue());
                //门店id          id类型 0-门店 1-云仓
                AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreIdAndType(store.getId().intValue(), 0);
                //   distribution_mode  配货 0按顺序 1全部 2手动
                //   配送 0按顺序 1全部 2手动 3第三方物流
                if (store.getDeliveryMode() == 2 && null != announcerBaseInfo) {
                    noticeType = 2;
                } else {
                    noticeType = 1;
                }
            }
            agedmallLgBaseInfo.setNoticeType(noticeType);
            agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
            //物流节点
            agedmallLgBaseInfo.setLgStat(packageLogisticsType);
            //agedmallLgBaseInfo.setLgUserConf(lgBaseInfo.getLgUserConf()==null?"":lgBaseInfo.getLgUserConf());
            agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.START.getCode());
            agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
            baseInfoIdAndOrderSn.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
            baseInfoIdAndOrderSn.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        } else {

            JSONArray jsonArray = (JSONArray) JSONArray.toJSON(lgDataList);
            String lgDateJSONString = jsonArray.toJSONString();
            LogisticsBackUserAddressData userBackAddress = new LogisticsBackUserAddressData();
            LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(litemallOrderItem.getUserId());
            LitemallAddressExample litemallAddressExample = new LitemallAddressExample();
            litemallAddressExample.or().andUserIdEqualTo(litemallUser.getId());
            LitemallAddress litemallAddress = litemallAddressMapper.selectOneByExample(litemallAddressExample);

            userBackAddress.setProvince(litemallAddress.getProvince());
            userBackAddress.setCity(litemallAddress.getCity());
            userBackAddress.setVillage(litemallAddress.getCounty());
            userBackAddress.setUserName(litemallUser.getUsername());
            userBackAddress.setPhone(litemallUser.getMobile());
            userBackAddress.setGender(litemallUser.getGender().intValue());
            userBackAddress.setAddress(litemallAddress.getAddress());
            userBackAddress.setDetail(litemallAddress.getAddressDetail());
            userBackAddress.setHosId(litemallAddress.getHospitalId());
            userBackAddress.setHosName(litemallAddress.getHospitalName());
            userBackAddress.setIsHos(litemallAddress.getIsHospital());
            userBackAddress.setLat(litemallAddress.getLat());
            userBackAddress.setLng(litemallAddress.getLng());
            // 添加物流节点
            AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
            agedmallLgBaseInfo.setOrderCode(bigOrder.getOrderSn());
            //购买
            agedmallLgBaseInfo.setLgType(LgType);
            //归还和退货需要   userBackAddress
            if (LgType.equals(LgBaseInfoLgType.GIVEBACK.getCode()) || LgType.equals(LgBaseInfoLgType.RETURNTHEGOODS.getCode())) {
                agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIdsList, userBackAddress));
            } else {
                agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIdsList, null));
            }
            agedmallLgBaseInfo.setUserName(bigOrder.getConsignee());
            agedmallLgBaseInfo.setPhone(bigOrder.getMobile());
            agedmallLgBaseInfo.setAddresss(bigOrder.getAddress());
            agedmallLgBaseInfo.setWarehouseType(litemallGoodsList.get(0).getStockType() == 3 ? 1 : 0);
            //LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfoList.get(i).getLgContent());
            agedmallLgBaseInfo.setLgUserConf(lgDateJSONString);
            //物流模式：1 门店，2第三方物流
            agedmallLgBaseInfo.setLgMode(deliveryType.byteValue());
            Integer noticeType = 0;
            //                           0-门店 1-链条锁 2-衣柜锁 3-云仓
            if (litemallGoodsList.get(0).getStockType() == 3) {
                AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(litemallGoodsList.get(0).getStoreId());
                agedmallLgBaseInfo.setWarehouseAddress(cloudHouse.getAddressDetail());
                agedmallLgBaseInfo.setStoreId(cloudHouse.getId());
                noticeType = 2;
            } else {
                AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(litemallGoodsList.get(0).getStoreId().longValue());
                agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
                agedmallLgBaseInfo.setStoreId(store.getId().intValue());
                //门店id          id类型 0-门店 1-云仓
                AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreIdAndType(store.getId().intValue(), 0);
                //   distribution_mode  配货 0按顺序 1全部 2手动
                //   配送 0按顺序 1全部 2手动 3第三方物流
                if (store.getDeliveryMode() == 2 && null != announcerBaseInfo) {
                    noticeType = 2;
                } else {
                    noticeType = 1;
                }
            }
            agedmallLgBaseInfo.setNoticeType(noticeType);
            //物流节点
            agedmallLgBaseInfo.setLgStat(packageLogisticsType);
            agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.START.getCode());
            agedmallLgBaseInfoMapper.insertSelective(agedmallLgBaseInfo);
            //返回 baseinfoId 和 小程序下单的号
            baseInfoIdAndOrderSn.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
            baseInfoIdAndOrderSn.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        }

        //手动配送配货退货取回维护
        if (!"sort".equals(deliveryUserId) && !"all".equals(deliveryUserId) && !"".equals(deliveryUserId) && (!"sort".equals(packUserId) && !"all".equals(packUserId)) && (!"".equals(packUserId))) {
            if ("".equals(maintainId)) {  //&& !"all".equals(maintainId) && !"sort".equals(maintainId)
                insertAgedmallLgMissionManRecord(deliveryUserId, baseInfoIdAndOrderSn.getBaseInfoId(), agedmallLgMissionManRecordMissionType);
            } else {
                //换货时使用
                //换货送货
                insertAgedmallLgMissionManRecord(deliveryUserId, baseInfoIdAndOrderSn.getBaseInfoId(), agedmallLgMissionManRecordMissionType);
                //换货取货
                insertAgedmallLgMissionManRecord(deliveryUserId, baseInfoIdAndOrderSn.getBaseInfoId(), LogisticsMissionTypeEnum.CHANGE_PICK_UP.getCode());
                //维护
                insertAgedmallLgMissionManRecord(maintainId, baseInfoIdAndOrderSn.getBaseInfoId(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
            }
            //lgMissionType
            List<Integer> integerList = logisticBusiBaseServiceImpl.backstageManagementToPlaceAnOrder(null, baseInfoIdAndOrderSn.getBaseInfoId(), lgMissionType);
            //接单
            /**
             * Integer manId, Integer missionId, Integer messageType
             */
            //接单
            //类型0-配货 1-送货 2-取货 3-维护 4-医生抢单
            logisticBusiBaseServiceImpl.receiveOrderEvent(Integer.parseInt(packUserId), integerList.get(0), null);
            //手动配货或者维护
        } else if ((!"sort".equals(packUserId) && !"all".equals(packUserId) && !"".equals(packUserId) && ("sort".equals(deliveryUserId) || "all".equals(deliveryUserId) || "".equals(deliveryUserId)))) {
            //lgMissionType
            List<Integer> integerList = logisticBusiBaseServiceImpl.backstageManagementToPlaceAnOrder(null, baseInfoIdAndOrderSn.getBaseInfoId(), lgMissionType);
            //接单
            /**
             * Integer manId, Integer missionId, Integer messageType
             */
            //接单
            //类型0-配货 1-送货 2-取货 3-维护 4-医生抢单
            logisticBusiBaseServiceImpl.receiveOrderEvent(Integer.parseInt(packUserId), integerList.get(0), null);
            //暂时不用
        } else if (!"sort".equals(deliveryUserId) && !"all".equals(deliveryUserId) && !"".equals(deliveryUserId) && ("sort".equals(packUserId) || "all".equals(packUserId) || "".equals(packUserId))) {
            insertAgedmallLgMissionManRecord(deliveryUserId, baseInfoIdAndOrderSn.getBaseInfoId(), agedmallLgMissionManRecordMissionType);
        }
        return baseInfoIdAndOrderSn;
    }

    /**
     * @param UserId      操作人员的id
     * @param baseInfoId  包裹的id
     * @param MissionType 任务类型
     */
    public void insertAgedmallLgMissionManRecord(String UserId, Integer baseInfoId, Integer MissionType) {
        AgedmallLgMissionManRecord agedmallLgMissionManRecord = new AgedmallLgMissionManRecord();
        agedmallLgMissionManRecord.setManId(Long.parseLong(UserId));
        agedmallLgMissionManRecord.setBaseInfoId(baseInfoId.longValue());
        //lgMissionType
        agedmallLgMissionManRecord.setMissionType(MissionType);
        //有没有使用 0未使用 1已使用
        agedmallLgMissionManRecord.setIsUse(0);
        agedmallLgMissionManRecordMapper.insertSelective(agedmallLgMissionManRecord);
    }

    public int updateChildOrderStatus(String childOrderCode, int status) {
        logger.debug("更新子订单状态:{},{}", childOrderCode, status);
        LitemallOrderItemExample itemExample = new LitemallOrderItemExample();
        itemExample.createCriteria().andChildOrderCodeEqualTo(childOrderCode);
        LitemallOrderItem orderItem = new LitemallOrderItem();
        orderItem.setOrderStatus((short) status);
        return litemallOrderItemMapper.updateByExampleSelective(orderItem, itemExample);
    }
}
